使用指向自身的指针初始化成员变量

Initializing member variable with pointer to itself

我听说以下是有效的并且 x 未初始化就好像它是 int x;:

int x = x;

这个呢?这段代码是否等同于上面的:

struct Foo
{
    Foo(int Foo::*p) : x(this->*p) { }
    int x;
};

int main() {
    Foo f(&Foo::x);
}

f.x还未初始化吗?我有未定义的行为吗?

Is this code equivalent to the above:

我会这么认为,是的,因为你本质上是在做: x(x),只是用一个指针读取x的当前值作为输入值,但是x有尚未初始化。

C++14 清楚地表明使用 indeterminate value is undefined behavior,来自 8.5 部分(强调我的 ):

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17 [expr.ass]). [Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2 [basic.start.init]. —end note] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:

唯一的例外是 unsigned char。这可能就是为什么他们将示例部分 3.3.2 更改为:

int x = 12;
{ int x = x; }

收件人:

unsigned char x = 12;
{ unsigned char x = x; }

我没有看到任何排除您的示例的例外情况。

x 在初始化之前具有不确定的值,但随后您在初始化期间访问它的值会调用未定义的行为。