最小示例:
#include <iostream>
using namespace std;
class myint{
public:
int x;
myint(int x) { this->x = x;}
~myint() {cout << "DEL" << endl; }
myint operator += (int const &y) { this->x += y; return y;}
};
int main() {
myint i = myint(2);
i += 3;
}
我很困惑为什么对象i被破坏了两次。如何避免这种情况?我将有大对象,并希望优化代码。使用基本运算符时,我不希望创建新对象。
答案 0 :(得分:0)
您为什么要返回y
?您应该返回*this
。还要使返回类型为myint&
。
#include <iostream>
using namespace std;
class myint {
public:
int x;
myint(int x) { this->x = x; }
~myint() { cout << "DEL" << endl; }
myint& operator += (int const &y) { this->x += y; return *this; }
};
int main() {
myint i = myint(2);
i += 3;
}
答案 1 :(得分:0)
在您的示例中,当return y;
编译器将进行隐式转换并自行创建myint
时。看看Explicit keyword。
因此,由于在一个对象中创建了两个对象。主函数中的第一个对象,operator +=
中的第二个临时对象。当main
函数完成时,当我们有两个对象时,会有两个描述符调用。
解决方案
使用引用和显式关键字以确保安全:
#include <iostream>
using namespace std;
class myint {
public:
int x;
explicit myint(int x) { this->x = x;}
~myint() {cout << "DEL " <<endl; }
myint& operator += (int const &y) { this->x += y; return *this;}
};
int main() {
myint i = myint(2);
i += 3;
}