【发布时间】:2020-10-07 23:45:17
【问题描述】:
我正在为我的 c++ 代码编写 class::operator=,并尝试在此代码 sn-p 中克隆类参数 right。
myClass & myClass::operator =(const myClass &right){
myClass *abcde = new myClass(right);
myClass coolvar(right); //this and the previous line work, but don't update the class
*this = *abcde; //uses = operator, so infinitely loops
myClass *this = new myClass(right); // doesn't work [expected unqualified-id]
myClass this(right); // doesn't work [expected unqualified-id]
}
但是,我找不到正确重写指针的方法,比如使用*this = *abcde,或者像底部两行那样调用类本身的构造函数。我该怎么办?
【问题讨论】:
-
您需要手动更新字段。这些试图利用复制构造函数的快捷方式将不起作用。此外,您应该接受引用
const myClass &right以避免不必要的复制构造函数调用。 -
注意:通过按值传入
right,您将接近能够应用Copy and Swap Idiom. -
如果我理解你的意图,你想调用复制构造函数来构造已经构造好的
*this?那么到程序结束时,构造函数调用会比析构函数调用多吗?这往往是灾难的根源。 -
@user4581301 默认不复制和交换。它经常扼杀你的表现。
-
不要使用手动内存管理,所有问题都会迎刃而解。
标签: c++ constructor operator-keyword