gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:14:34 29 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

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

// 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com