与显式初始化相比,了解C++中的复制初始化

Meh*_*dad 8 c++ constructor initialization

为什么第一个注释行正确编译,而第二个没有?

为什么可以a将自己作为构造函数参数,但b不能?
这两个人做的不一样吗?

class Foo { Foo &operator =(Foo const &); /* Disable assignment */ };

int main()
{
    Foo a = a;  // OK
    Foo  b(b);  // error C2065: 'b' : undeclared identifier
}
Run Code Online (Sandbox Code Playgroud)

更新

由于它看起来像编译器依赖,似乎问题比我想象的更严重.
所以我想问题的另一部分是,以下代码是否有效?

它在GCC中出错,但Visual C++执行得很好.

int main()
{
    int i = 0;
    { int *i(&i); }
    return i;
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 4

在您的第一个代码中,两个声明都应该编译。海湾合作委员会就在那里。Visual C++ 编译器有错误。

在第二个代码中,内部声明不应编译。GCC也是对的,VC++是错的。

GCC 在这两种情况下都是正确的

从语法的角度来看,像int a=a+100;and这样的代码int a(a+100);很好。它们可能会调用未定义的行为,具体取决于它们是在静态存储持续时间还是自动存储持续时间中创建的。

int a = a + 100; //well-defined. a is initialized to 100
                 //a on RHS is statically initialized to 0
                 //then a on LHS is dynamically initialized to (0+100).
void f()
{
   int b = b + 100; //undefined-behavior. b on RHS is uninitialized

   int a = a + 50; //which `a` is on the RHS? previously declared one?
                   //No. `a` on RHS refers to the newly declared one.
                   //the part `int a` declares a variable, which hides 
                   //any symbol with same name declared in outer scope, 
                   //then `=a+50` is the initializer part.
                   //since a on RHS is uninitialized, it invokes UB
}
Run Code Online (Sandbox Code Playgroud)

请阅读与上述每个声明相关的注释。

请注意,具有静态存储持续时间的变量在编译时静态初始化为零,如果它们具有初始化程序,那么它们也会运行时动态初始化。但是具有自动存储期限的 POD 类型的变量不是静态初始化的。

有关静态初始化与动态初始化的更多详细说明,请参阅: