我正在寻找以下解释的答案(摘自《 C ++之路》这本书]
MyClass& operator=(const MyClass&) // copy asignment: clean up target and copy
我从来没有清理目标 (或者至少我不明白这是什么意思)复制时是这样的:
move
吗?清理目标的确切含义是什么?
const
,所以我不会能够修改它在书的下面指出:
MyClass& operator=(MyClass&&) // move assignment: clean up target and move
在这里清理目标很有意义,因为这是我对move
-ing的工作方式的理解
假设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.
}
多亏@PaulMcKenzie
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;
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.
}