副本分配应该做什么

问题描述 投票:0回答:1

我正在寻找以下解释的答案(摘自《 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的工作方式的理解

c++ copy move
1个回答
1
投票

假设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.
  }
© www.soinside.com 2019 - 2024. All rights reserved.