2

I recently came across a rather interesting serialization approach that utilized the transparency (common undefined behavior among compilers?) of uninitialized variables for "efficient" deserialization.

Memory is allocated and assigned a predetermined value. Placement new is then used to instantiate a struct (for example a complex inplace data structure) "initializing" the uninitialized variables to the value of the underlying memory. (see code below)

Besides from being rather risky and possibly not a very agreeable coding convention... I was just wondering whether anyone had come across this method or more importantly -- what is it called?

class SomeClass {
public:
  SomeClass() {}

  int someInt;
};

int main(...) {
  int dummy = 42;

  int *pSomeClass = new (&dummy) SomeClass();
  cout << pSomeClass->someInt << endl;
}

This will print out the number 42... neato!

Shawn
  • 47,241
  • 3
  • 26
  • 60
Maigo
  • 69
  • 4

2 Answers2

5

It's called "relying on UB" or, in laymen's terms, "foolishness".

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

I have seen this done in eCos, an RTOS, to initialize some of their kernel objects.

As pointed out by Tomalak one of the draw-backs is no virtual functions allowed. They try to ensure that by testing for equal size sizeof(kernel object) == sizeof(variable used for initialization).

Their code although was way more complex using a C-struct to mimic the C++ class member variables for the c interface instead of using C functions to get/set the variables in the C++ class

Although the behaviour they went for there was the exact opposite, they used values from the C++ class, set in the constructor, to fill the memory from placement new.

I do not advise on doing this tho.

RedX
  • 14,749
  • 1
  • 53
  • 76