复制作业应该做什么
What should a copy assignment do
我正在寻找以下解释的答案(来自书"A tour of C++")
MyClass& operator=(const MyClass&) // copy asignment: clean up target and copy
我从来没有清理过目标 (或者至少我不明白它是做什么的mean) 复制时 so:
- 复制的概念不就是有两个相同的东西吗?
- 如果我清理目标,那不是
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 && @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.
}
我正在寻找以下解释的答案(来自书"A tour of C++")
MyClass& operator=(const MyClass&) // copy asignment: clean up target and copy
我从来没有清理过目标 (或者至少我不明白它是做什么的mean) 复制时 so:
- 复制的概念不就是有两个相同的东西吗?
- 如果我清理目标,那不是
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 && @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.
}