对 C++ 的理解混乱;标准
在 C++98 中
12.6.2/4 :在类 X 的构造函数调用完成后,如果 X 的成员未在构造函数的 mem-initializers 中指定,也不是默认初始化,也不是在构造函数主体执行期间初始化,该成员具有不确定的值。
在构造函数主体执行期间初始化是什么意思?可以在构造函数体内初始化成员吗?
In C++98
12.6.2/4 : After the call to a constructor for class X has completed, if a member of X is neither specified in the constructor's mem-initializers, nor default-initialized, nor initialized during execution of the body of the constructor, the member has indeterminate value.
What does nor initialized during execution of the body of the constructor mean? Can a member be initialized inside the body of the constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在构造函数主体执行期间初始化是不正确的恕我直言。
C++03 中的措辞已从未初始化(在 C++98 中)更改为未给定值
nor initialized during execution of the body of the constructor is not correct IMHO.
The wordings have been changed in C++03 from nor initialized (in C++98) to nor given a value
其实很简单。类/结构成员可以包含具有默认构造函数的对象,但如果它们不包含默认构造函数,并且您不必费心在初始化程序列表中为它们提供值,也不必在构造函数的主体中设置它们,那么基本上它们的内存占用 - 从堆栈或堆中为它们搜寻的任何内容 - 仍然会有旧的垃圾在那里,即不确定的值。
考虑:
这里,
x1
和x2
由X
的构造函数显式初始化,而x4
- 是一个 < code>std::string - 默认构造为“”/长度 0。但是,x3
可以是任何内容 - 并且在设置之前不应读取(它是未定义的行为,并且确实可能会影响某些系统 - 考虑到它占用的内存的位模式甚至可能不是双精度值的有效值,因此从中读取可能会触发一些 CPU 异常/陷阱/中断)。It's actually very simple. class/struct members can include objects with default constructors, but if they don't, and you don't bother to give them a value in the initialiser list, nor set them within the body of the constructor, then basically the memory that they occupy - whatever was scrounged for them from the stack or heap - will still have old garbage in there, i.e. an indeterminate value.
Consider:
Here,
x1
andx2
are explicitly initialised byX
's constructor, andx4
- being astd::string
- is default constructed to be "" / length 0.x3
, however, could be anything - and shouldn't be read from until after it's been set (it's undefined behaviour and really could bite on some systems - consider that the bit pattern of the memory it occupies may not even be a valid value for a double, so reading from it might trigger some CPU exception/trap/interrupt).