假设我重载了诸如~and之类的 C++ 运算符=,就像这样
Foobar& Foobar::operator~() const {
Foobar *result = new Foobar();
// compute *result based on *this
return *result;
}
Foobar& Foobar::operator=(Foobar& arg) {
// compute *this based on arg
// return *this for transitivity
return *this;
}
出于向后兼容性和性能原因,运算符必须返回Foobar&,而不是指针。Foobar
然后,我班的用户会写这样的东西:
Foobar obj0, obj1;
obj1 = ~obj0;
现在返回 from ~,它new丢失了,所以没有办法delete,new所以没有内存泄漏?如果有泄漏,如何设计这样就没有了?