我有这样的类(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;}
};
当我想要对 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 .
关于c++ - 静态分配对象的值初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59876209/