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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…