Suppose I have a C++ struct that has both POD and non-POD member variables:
struct Struct {
std::string String;
int Int;
};
and in order for my program to produce reproduceable behavior I want to have all member variables initialized at construction. I can use an initializer list for that:
Struct::Struct() : Int() {}
the problem is as soon as I need to change my struct and add a new POD member variable(say bool Bool
) I risk forgetting to add it to the initializer list. Then the new member variable will not be value-initialized during struct construction.
Also I can't use the memset()
trick:
Struct::Struct()
{
memset( this, 0, sizeof( *this ) ); //can break non-POD member variables
}
because calling memset()
to overwrite already constructed non-POD member variables can break those.
Is there a way to enforce value-initialization of all POD member variables without explicitly adding their initialization in this case?
const
. Especially when they are allpublic
it really makes sense to force immutability. You can use array initialize syntax to create instances:Struct s = { "...", 0 };
– Busterstd::shared_ptr
in this case. Or maybe decide to properly encapsulate the members and remove theconst
. – Busterconst
isn't a proper solution because you've changed what the class can do. There are other solutions that solve the problem that don't change the usability. While this doesn't eliminate the possibility your solution could be applied to different situations (which I never said), it does mean your solution falls a short relative to others. – Diplomatics