静态分配对象的值初始化

Value initialization of statically allocated object

我有这样的class:

class Car {
    int x;
public:
    Car() {cout << "Init car" << endl;}
    Car(const Car & c) { cout << "Copy car" << endl;}
    Car(const Car && c) { cout << "Move car" << endl;}
};

当我想初始化 class 的对象时 Car:

Car c = Car();

仅调用默认构造函数。既然有赋值,为什么不调用复制构造函数或移动构造函数?

因为 copy elision,C++17 保证了这一点。

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

  • In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:

    T f() {
        return T();
    }
    
    T x = T(T(f())); // only one call to default constructor of T, to initialize x
    

PS:T x = T();不是赋值而是初始化,更准确地说是copy initialization.