【问题标题】:What should a copy assignment do复制作业应该做什么
【发布时间】:2020-04-17 19:34:44
【问题描述】:

我正在寻找以下解释的答案(来自“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 的工作原理

【问题讨论】:

  • 那个目标是调用操作符的对象,而不是传递的参数
  • 大概他们的意思是在从被分配对象复制它们之前清理/释放被分配对象所拥有的任何资源
  • 可能意味着您在复制发生之前删除了当前对象的旧残余(例如分配的内存)。但这无论如何都是个坏建议,因为如果您在复制完成之前开始更改 *this 的值而不抛出异常,那么赋值运算符就有缺陷。通常做的是copy / swap,在这里你使用传入对象的临时副本,并对this的成员和临时对象做简单的std::swap's
  • 目标是=左侧的值。

标签: c++ copy move


【解决方案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 && @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.
  }

【讨论】:

  • 哇,很简单。谢谢
  • 您的代码存在我在 cmets 中提到的缺陷。在分配内存之前删除that。如果new 抛出异常怎么办?或者Owned 是一个可以抛出构造的类?
  • 一些关于这个主题的额外阅读:The Rule of Three/Five/Zero。你想要争取的是尽可能多地使用零规则。这意味着资源的直接所有者需要支持三个或五个,而其他人绝对什么都不做,资源所有者和编译器为他们完成所有工作。
  • @PaulMcKenzie 只知道我明白你之前在回答中告诉我的内容......
  • 防止自赋值检查可以去掉。该例程是自我分配正确的,这更好。
猜你喜欢
  • 2014-10-26
  • 2019-10-20
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多