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?
The cleanest way would be to write the auto-initialzed template class
initialized<T>:EDIT: I realize now it can be made even more flexible by allowing you to declare
initialized<Struct>. This means that you can declare initialization without modifying the originalStruct. The default initialization ‘T()’ was inspired on Prasoons answer.This compiles, but may need more conversion operators, handling of keywords like volatile, etc. But you get the idea.