是否有一种方法来创建一个C ++ struct值 - 初始化所有POD成员变量? [英] Is there a way to make a C++ struct value-initialize all POD member variables?
问题描述
假设我有一个包含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 )我冒着忘记把它添加到初始化列表的风险。
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()
trick:
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?
推荐答案
最简单的方法是编写自动初始化模板类初始化< T>
:
The cleanest way would be to write the auto-initialzed template class initialized<T>
:
编辑:我意识到现在可以通过允许您声明初始化< Struct>
。这意味着您可以在不修改原始 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;
}
这样编译,但可能需要更多的转换操作符,等等,但你得到的想法。
This compiles, but may need more conversion operators, handling of keywords like volatile, etc. But you get the idea.
这篇关于是否有一种方法来创建一个C ++ struct值 - 初始化所有POD成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!