1

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?

6
  • 4
    = default; seems enough Commented Apr 19, 2016 at 8:28
  • 1
    std::shared_ptr<DataType> data takes care of all this for you. Commented Apr 19, 2016 at 8:30
  • And there is also the move constructor/assignment. Commented Apr 19, 2016 at 8:55
  • Ok, so it seems that there is no particular warning flag to be raised as to the logic of the implementation, except for noting that default is all you really need in this case. I guess c++11 is succeeding in making things easier at last... Commented Apr 19, 2016 at 9:01
  • This belongs on Code Review. Commented Apr 19, 2016 at 22:37

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's a good point, thanks. However this is more a way to obtain what I already have with less effort.
1

I see one minor pitfall. Typically the default constructor should not be defaulted, as it will create a null data_ pointer. I think in general it is more desirable to have the default constructor to create a data_ pointer holding a default-constructed DataType object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.