Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

constructor - Is there a way to make a C++ struct value-initialize all POD member variables?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Linked Question here

Is there a way to enforce value-initialization of all POD member variables without explicitly adding their initialization in this case?

I am not sure whether something like that is possible [directly] or not but the following works

prasoon@prasoon-desktop ~ $ cat check.cpp && clang++ check.cpp && ./a.out
#include <iostream>
struct Struct {
    std::string String;
    int Int;
    bool k;
    // add add add
};

struct InStruct:Struct
{
   InStruct():Struct(){}
};

int main()
{
   InStruct i;
   std::cout<< i.k << "  " << i.Int << std::endl; 
}
0  0
prasoon@prasoon-desktop ~ $ 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...