Предположим, MyClass имеет собственный указатель
class MyClass {
Owned *that;
public:
...
MyClass& operator=(const MyClass&other) // copy asignment: clean up target and copy
{
Owned = other->owned;
}
Что происходит с памятью, на которую указывает? это утечка. Так что вместо этого сделайте
MyClass& operator=(const MyClass&other) // copy asignment: clean up target and copy
{
if (this == &other) // prevent self assignment as this would in this case be a waste of time.
return *this;
delete that; // clean up
that = new Owned(*other->that); // copy
return *this; // return the object, so operations can be chained.
}
Лучше благодаря @ PaulMcKenz ie && @ Eljay
MyClass& operator=(const MyClass&other) // copy asignment: clean up target and copy
{
Owned *delayDelete = that;
that = new Owned(*other->that); // copy, if this throws nothing happened
delete delayDelete; // clean up
return *this; // return the object, so operations can be chained.
}