对 C++ 的理解混乱;标准

发布于 2024-10-06 06:01:20 字数 254 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残疾 2024-10-13 06:01:20

在构造函数主体执行期间初始化是不正确的恕我直言。

C++03 中的措辞已从未初始化(在 C++98 中)更改为未给定值

在类 X 的构造函数调用完成后,如果 X 的成员既未在构造函数的 mem-initializers 中指定,也未默认初始化,也未进行值初始化,也未给定值 在执行构造函数主体期间,该成员具有不确定的值。

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

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 value-initialized, nor given a value during execution of the body of the constructor, the member has indeterminate value.

感受沵的脚步 2024-10-13 06:01:20

其实很简单。类/结构成员可以包含具有默认构造函数的对象,但如果它们不包含默认构造函数,并且您不必费心在初始化程序列表中为它们提供值,也不必在构造函数的主体中设置它们,那么基本上它们的内存占用 - 从堆栈或堆中为它们搜寻的任何内容 - 仍然会有旧的垃圾在那里,即不确定的值。

考虑:

struct X
{
    X() : x1(1) { x2 = 2; }
    double x1, x2, x3;
    std::string x4;
};

这里,x1x2X 的构造函数显式初始化,而 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:

struct X
{
    X() : x1(1) { x2 = 2; }
    double x1, x2, x3;
    std::string x4;
};

Here, x1 and x2 are explicitly initialised by X's constructor, and x4 - being a std::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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文