c++ - 静态分配对象的值初始化

标签 c++ initialization

我有这样的类(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/

相关文章:

c++ - 在自己的构造中使用对象有什么问题吗?

c++ - 十字架初始化的迹象是什么?

c - 如何在不使用循环的情况下在 C 中初始化 N 维数组

c - "strings"声明的 gcc 数组失败

C++检查xs :double datatype

c++ - Opencv如何从相机读取单帧

c++ - 为什么 std::allocator 在 C++17 中丢失了成员类型/函数?

c - 使用 malloc 初始化一个 char 指针数组

c++ - 如何用函数的结果初始化静态成员数组?

c++ - 删除命令提示符