默认初始化和值初始化之间的歧义

Ambiguity between default-initialization and value-initialization

找了很多文章解释"default-initialization and value-initialization"的区别,其实我没看清楚

这是一个例子:

class A{
   public:
      int x;
};


int main(){
    A a;// default initialization so x has undefined value.
    A b = A(); // value initialization so x is a scalar thus it is value initialized to 0

}

上面我猜是可以的,但是这里:

int value = 4; // is this considered a value-initialization?

请帮助我理解这两种初始化形式之间的主要区别。

A a;Adefault initialization, as the effect the default constructor of A is used for initialization. Since the implicitly-generated default constructor 什么都不做,a.x 有不确定的值。

A()value initialization,

if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;

注意与default initialization, A has an implicitly-defined default constructor, and the object is zero-initialized的区别;所以临时对象 A() 的数据成员 x 将被初始化为 0.

A b = A();直接就是copy initialization, in concept b is initialized from the temporary object A(), so b.x will be initialized to 0 too. Note that because of copy elision, since C++17 b is guaranteed to be value-initialized; copy/move 构造被省略。

int value = 4; 也是 copy initializationvalue 将被初始化为 4.