Search code examples
c++c++11shared-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. 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=.

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?


Solution

  • 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.