有没有办法让 C++ 结构值初始化所有 POD 成员变量?
假设我有一个包含 POD 和非 POD 成员变量的 C++ 结构:
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() {}
问题在于,一旦我需要更改结构并添加新的 POD 成员变量(比如 bool Bool
),我就有可能忘记将其添加到初始化列表中.那么新的成员变量就不会在struct构造过程中进行值初始化.
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.
我也不能使用 memset()
技巧:
Also I can't use the memset()
trick:
Struct::Struct()
{
memset( this, 0, sizeof( *this ) ); //can break non-POD member variables
}
因为调用 memset()
来覆盖已经构造的非 POD 成员变量会破坏它们.
because calling memset()
to overwrite already constructed non-POD member variables can break those.
在这种情况下,有没有办法在不显式添加初始化的情况下强制对所有 POD 成员变量进行值初始化?
Is there a way to enforce value-initialization of all POD member variables without explicitly adding their initialization in this case?
推荐答案
最简洁的方法是编写自动初始化的模板类 initialized
:
The cleanest way would be to write the auto-initialzed template class initialized<T>
:
我现在意识到通过允许您声明 initialized
可以使其更加灵活.这意味着您可以在不修改原始 Struct
的情况下声明初始化.默认初始化 'T()' 的灵感来自 Prasoons 的答案.
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 original Struct
. The default initialization 'T()' was inspired on Prasoons answer.
template<class T>
struct initialized
{
public:
initialized()
{ value = T(); }
initialized(T t)
{ value = t; }
initialized(const initialized<T>& x)
{ value = x.value; }
T* operator &() { return &value; }
operator T&() { return value; }
private:
T value;
};
struct PodStruct
{
std::string String;
int Int;
};
struct GlorifiedPodStruct
{
std::string String;
initialized<int> Int;
};
void Test()
{
GlorifiedPodStruct s;
s.Int = 1;
int b = s.Int;
int * pointer = &s.Int;
initialized<PodStruct> s2;
}
这可以编译,但可能需要更多的转换运算符,处理 volatile 等关键字.但你明白了.
This compiles, but may need more conversion operators, handling of keywords like volatile, etc. But you get the idea.
相关文章