c++ - 使用另一个(现有)对象创建新对象时会发生什么?

标签 c++ constructor initialization copy-constructor

我在一本书上看到,它说: 当我们使用另一个初始化新创建的对象时 - 使用复制构造函数创建一个临时对象,然后使用赋值运算符将值复制到新对象!

后来在书中我读到: 当使用另一个对象初始化新对象时,编译器创建一个临时对象,使用复制构造函数将其复制到新对象。临时对象作为参数传递给复制构造函数。

真的很困惑,到底发生了什么!!

最佳答案

我认为这些说法都不正确 - 没有调用复制赋值运算符。

我会这样描述发生的事情:

当您创建一个新对象作为现有对象的拷贝时,将调用复制构造函数:

// creation of new objects
Test t2(t1);
Test t3 = t1;

只有当您赋值给一个已经存在的对象时,复制赋值运算符才会被调用

// assign to already existing variable
Test t4;
t4 = t1;

我们可以用下面的小例子来证明这一点:

#include <iostream>

class Test
{
public:
    Test() = default;
    Test(const Test &t)
    {
        std::cout << "copy constructor\n";
    }
    Test& operator= (const Test &t)
    {
        std::cout << "copy assignment operator\n";
       return *this;
    }
};

int main()
{
    Test t1;

    // both of these will only call the copy constructor
    Test t2(t1);
    Test t3 = t1;

    // only when assigning to an already existing variable is the copy-assignment operator called
    Test t4;
    t4 = t1;

    // prevent unused variable warnings
    (void)t2;
    (void)t3;
    (void)t4;

    return 0;
}

输出:

copy constructor
copy constructor
copy assignment operator

working example

关于c++ - 使用另一个(现有)对象创建新对象时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37975574/

相关文章:

c++ - 使用成员函数调用可变参数模板函数

c++ - 如何通过计算新的 x 和 y 位置来围绕其中心旋转 Sprite ?

C++ 错误 C2512 : no appropriate default constructor available

C 中的复合语句表达式

C++ 前向声明和纯虚函数

C++:两个指向相同结构的指针 vector ,每个 vector 的排序不同

java - 如何设计构造函数?

reactjs - 如何使用 React Hooks 将带有构造函数的类转换为功能组件?

c# - 在配置文件中设置 DatabaseInitializerForType 以触发自定义初始化程序

python - 具有不同初始化参数的多重继承的真正解决方案