在链表中移动一个简单类的构造函数/赋值

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

我有一个简单的类,有一些简单的成员,并且没有分配。我计划添加一个移动构造函数/作业。这些原语不会比普通原语更有效。

问题一:为了让我的类更通用而这样做有意义吗?

有一个链接该类对象的内部列表。

问题二:我应该将移出的类保留在什么状态:在列表中还是从列表中删除?我打算将其从列表中删除。

更新:有一些关于使用编译器生成的动作的评论。我不能这样做,因为我必须处理一份内部清单。

所以,要么是手工制作的动作,要么没有。可能的代码片段如下,没有多线程。

class A {
 public:
  static void Run() {
       A* cur = list_;
       while(cur) {
           cur->DoWork();
           cur = cur->next_;
       }
  }
   
  virtual ~A() { Remove(); }

  A() : next_(), data_(), in_list_() {
  }

  A(int data) : next_(), data_(data), in_list() {
    Insert();
  }

  A(A const& other) : next_(), data_(other.data_), in_list() {
    Insert();
  }

  A(A&& other) : next_(), data_(other.data_), in_list() {
    other.Remove();
    Insert();
  }

  A& operator=(A const& other) {
    if (this != &other) {
       data_ = other.data_;
       Insert();
    }
    return *this;
  }

  A& operator=(A&& other) {
    if (this != &other) {
      data_ = other.data_;
      other.Remove();
      Insert();
    }
    return *this;
  }

 private:
    void DoWork() { <do-something-important-with-data>; }

    void Insert() {
      if (_in_list) {
        return;
      }
      ...;
      in_list_ = true;
    }

    void Remove() {
      if (!_in_list) {
        return;
      }
      ...;
      in_list_ = false;
    };

  A* next_;
  int data_;
  bool in_list_;

  static A* list_;
};

c++ move-semantics rule-of-five
1个回答
0
投票

经过评论中的讨论(谢谢大家),我似乎可以自己回答这个问题:(1)实现五规则只是为了支持 unique_ptr 是一个好主意,(2)源对象移动完成后,移动的名称不应出现在列表中。

© www.soinside.com 2019 - 2024. All rights reserved.