gpt4 book ai didi

c++ - 当我从赋值运算符按值返回时,首先调用复制构造函数的机制和依据是什么?

转载 作者:行者123 更新时间:2023-11-30 02:47:44 27 4
gpt4 key购买 nike

考虑这段代码及其输出:

class test {    
int a, b;

public:
test (int a, int b) : a(a), b(b) { cout << "Const" << endl;}

test (const test & t) {
cout << "Copy constructor" << endl;
cout << "Being copied to = " << this << " from " << &t << endl;
if (&t == this) {
cout << "returning" << endl;
return;
}
this->a = t.a;
this->b = 6;//t.b;
}

test operator=(const test & in) {
cout << "Assignment operator" << endl;
this->a = in.a;
this->b = in.b;
cout << "Being written to = " << this << " from "<< &in << endl;
return *this;
}

test get () {
test l = test (3, 3);
cout << "Local return " << &l << endl;
return l;
}

void display () {
cout << a << " " << b << endl;
}
};

int main () {
int i = 5, &ref = i;
test t(1,1), u(2,2);

u = t.get();
cout << "u address" << &u <<endl;
//cout << "u ka = " << &u << endl;
u.display();
}

输出:

Const
Const
Const
Local return 0x7fff680e5ab0
Assignment operator
Being written to = 0x7fff680e5a90 from 0x7fff680e5ab0
Copy constructor
Being copied to = 0x7fff680e5a80 from 0x7fff680e5a90
u address0x7fff680e5a90
3 3

我知道从赋值返回的方式是通过引用,但由于我是 C++ 的初学者,所以我试图了解它是如何工作的。地址 0x7fff680e5a80 是什么?这是从哪里来的?哪个对象在这里调用复制构造函数?我希望你(地址 0x7fff680e5a90)调用它。

最佳答案

让我们按照您的代码进行操作(我修改了您的构造函数以转储已构造的 this)。

首先,您实例化 t 和 u。

Const at 0x7fffffffdeb0
Const at 0x7fffffffdea0

然后调用 t.get,它初始化 l。

Const at 0x7fffffffdec0

然后你返回 l。

Local return 0x7fffffffdec0

此时通常会发生的复制构造函数被省略了。

Assignment operator from l to u
Being written to = 0x7fffffffdea0 from 0x7fffffffdec0

然后你按值返回赋值(你应该通过引用返回它),所以你从 u 复制到一个未存储的输出值(0x7fffffffde90 来自 u)

Copy constructor
Being copied to = 0x7fffffffde90 from 0x7fffffffdea0

然后你打印你。

u address0x7fffffffdea0

在 T 内。

为了摆脱困惑(和不必要的拷贝),您应该在执行任何赋值运算符时通过引用返回:

test& operator=(const test & in);

关于c++ - 当我从赋值运算符按值返回时,首先调用复制构造函数的机制和依据是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22564115/

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