构造器指定所有内置成员的零初始化? [英] Constructor to specify zero-initialization of all builtin members?
问题描述
对于类的构造函数,有没有更简单的方法来指定内置类型的所有成员应该被初始化为零?
Is there a simpler way for a class's constructor to specify that all members of built-in type should be zero-initialized?
此代码段在另一篇文章中出现:
This code snippet came up in another post:
struct Money
{
double amountP, amountG, totalChange;
int twenty, ten, five, one, change;
int quarter, dime, nickel, penny;
void foo();
Money() {}
};
结果证明问题是对象通过
and it turned out that the problem was that the object was instantiated via Money mc;
and the variables were uninitialized.
建议的解决方案是添加以下构造函数:
The recommended solution was to add the following constructor:
Money::Money()
: amountP(), amountG(), totalChange(),
twenty(), ten(), five(), one(), change()
quarter(), dime(), nickel(), penny()
{
}
但是,这是丑陋,不便于维护。很容易添加另一个成员变量,忘记将其添加到构造函数中的长列表中,可能导致在未初始化的变量突然停止获取 0
。
However, this is ugly and not maintenance-friendly. It would be easy to add another member variable and forget to add it to the long list in the constructor, perhaps causing a hard-to-find bug months down the track when the uninitialized variable suddenly stops getting 0
by chance.
推荐答案
您可以使用子对象初始化。成员工作,但是你需要限定所有访问。所以继承更好:
You can use a subobject to initialize en masse. A member works, but then you need to qualify all access. So inheritance is better:
struct MoneyData
{
double amountP, amountG, totalChange;
int twenty, ten, five, one, change;
int quarter, dime, nickel, penny;
};
struct Money : MoneyData
{
void foo();
Money() : MoneyData() {} /* value initialize the base subobject */
};
演示(刊登位置 new
请确保在创建对象之前内存不为0): http://ideone.com/P1nxN6
Demonstration (placement new
is used to make sure the memory is non-zero before object creation): http://ideone.com/P1nxN6
与问题中的代码略有不同: http:// ideone。 com / n4lOdj
Contrast with a slight variation on the code in the question: http://ideone.com/n4lOdj
在上述两个演示中, double
成员都被删除, / NaN编码。
In both of the above demos, double
members are removed to avoid possible invalid/NaN encodings.
这篇关于构造器指定所有内置成员的零初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!