Reputation: 2540
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?
Upvotes: 1
Views: 139
Reputation: 2540
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.
Upvotes: 1
Reputation: 4511
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.
Upvotes: 5