简体   繁体   English

使用std :: shared_ptr的共享数据类

[英]Shared data class using std::shared_ptr

I need a class that implements shared data semantics, and probably std::shared_ptr is a good place to start. 我需要一个实现共享数据语义的类,也许std::shared_ptr是一个不错的起点。 I think a typical implementation of such class could use an private shared_ptr to the shared data, and then implement at least copy constructor and operator= . 我认为此类的典型实现可以对共享数据使用私有的shared_ptr ,然后至少实现复制构造函数和operator=

Something like: 就像是:

class SharedDataClass {

public:
  SharedDataClass(const SharedDataClass& other)
  {
    data_ = other.data_;
  };

  SharedDataClass& operator=(const SharedDataClass& other)
  {
    data_ = other.data_;
    return *this;
  }

private:
  std::shared_ptr<DataType> data_;
};

I'd like to ask if anyone has some criticism to offer on the above implementation. 我想问一下是否有人对上述实现提出批评。 Is there any other member/operator that should be implemented for consistency? 是否还有其他成员/运营商应该实现一致性?

There is no need to implement a copy constructor or an assignment operator in this case. 在这种情况下,无需实现复制构造函数或赋值运算符。 Let the compiler defines the trivial default ones for you, the shared_ptr will do the job you are expecting. 让编译器为您定义简单的默认值,shared_ptr将完成您期望的工作。

I see one minor pitfall. 我看到一个小陷阱。 Typically the default constructor should not be defaulted, as it will create a null data_ pointer. 通常,默认构造函数不应为默认构造函数,因为它将创建一个空的data_指针。 I think in general it is more desirable to have the default constructor to create a data_ pointer holding a default-constructed DataType object. 我认为一般来说,最好使用默认构造函数来创建一个data_指针,该指针包含一个默认构造的DataType对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM