赋值构造在如下二种情况下被触发:
1. 对象以值传递方式从函数返回,且接受返回值的对象已经初始化过
2. 对象直接赋值给另一个对象,且接受值的对象已经初始化过
#include <stdio.h>
class A {
public:
int* x;
int y;
A() = default;
A (const A& a) {
printf ("拷贝构造\n");
this->x = a.x;
this->y = a.y;
}
A& operator= (const A& a) {
printf ("赋值构造\n");
this->x = a.x;
this->y = a.y;
return *this;
}
A (int t) {
x = new int (0);
y = t;
printf ("address: %x, point: %x, value: %d\n", this, x, y);
}
~A() {
printf ("delete %x\n", this);
}
};
A f () {
A ret (3);
printf ("stack address: %x, point: %x, value: %d\n", &ret, ret.x, ret.y);
return ret;
}
void g (A ret) {
printf ("stack address: %x, point: %x, value: %d\n", &ret, ret.x, ret.y);
}
1.对象以值传递方式从函数返回,且接受返回值的对象已经初始化过
int main() {
A c;
c = f();
printf ("global address: %x, point: %x, value: %d\n", &c, c.x, c.y);
return 0;
}
Output:
address: 983c4a80, point: 1c6ec20, value: 3
stack address: 983c4a80, point: 1c6ec20, value: 3
赋值构造
delete 983c4a80
global address: 983c4a70, point: 1c6ec20, value: 3
delete 983c4a70
2.对象直接赋值给另一个对象,且接受值的对象已经初始化过
int main() {
A a(1);
A c;
c = a;
printf ("global address: %x, point: %x, value: %d\n", &c, c.x, c.y);
return 0;
}
Output:
address: b12903c0, point: 1531c20, value: 1
赋值构造
global address: b12903d0, point: 1531c20, value: 1
delete b12903d0
delete b12903c0
赋值构造禁用
1.将赋值运算符声明为私有,并不予实现
class Uncopyable
{
private:
Uncopyable &operator=(const Uncopyable &);
};
2.使用delete
class Uncopyable
{
Uncopyable &operator=(const Uncopyable &)=delete;
};