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() {}
};
事实证明,问题在于对象是通过Money mc;
实例化的,而变量未初始化.
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
用于在对象创建之前确保内存非零):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.
这篇关于指定所有内置成员的零初始化的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:指定所有内置成员的零初始化的构造函数?
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01