ndsev / zserio

zero sugar, zero fat, zero serialization overhead
https://zserio.org/
BSD 3-Clause "New" or "Revised" License
108 stars 26 forks source link

[C++] Force initialization of objects in constructor #267

Open frank-aurich opened 3 years ago

frank-aurich commented 3 years ago

For objects that need to be initialized, the initialization values should be part of the constructor.
Currently, you can create such objects just fine, but when trying to write them using BitStreamWriter, an exception will be thrown.

Consider an object:

struct Position(uint shift)
{
  int<(31-shift) + 1> x;
  int<(31-shift) + 1> y;
}

The generated C++ code will allow to write this code that compiles just fine, but throws an exception at runtime:

BitStreamWriter bsw;
Position pos(162791424, 609027496);
pos.write(bsw); // throws exception

Instead we have to explicitly initialize the object:

BitStreamWriter bsw;
Position pos(162791424, 609027496);
origin.initialize(0);
pos.write(bsw); // throws exception

Proposal

The shift value should be part of the constructor:

BitStreamWriter bsw;
Position pos(162791424, 609027496, 0);
pos.write(bsw);
mikir commented 3 years ago

Hi,

first of all, thank you very much for your contributions and for all valuable feedback!

Regarding this proposal, we could introduce this new constructor but not as a replacement of initialize method. We see that this new constructor could be handy for top level structures.