Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rule of three with smart pointer?

Tags:

c++

I'm a little confused by using "rule of three" with smart pointers. If I have a class whose only data member is a smart pointer, do I need to explicitly define destructor, copy constructor, and assignment operator?

My understanding is that since smart pointer will handle the resource automatically, then I don't need to explicitly define destructor, and thus I shouldn't need to do so for the other two based on rule of three. However, I'm not sure if the default copy constructor is good enough for smart pointers such as shared_ptr.

Thank you for your help!

like image 291
EXP0 Avatar asked Sep 30 '11 20:09

EXP0


People also ask

Are smart pointers templated classes?

Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator.

What is a smart pointer and when should I use one?

A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way. Smart pointers should be preferred over raw pointers.

Is Unique_ptr an example of Raii idiom?

yes, it's an RAII class.

What is Rule of 3 and Rule of 5 in C++?

The rule of three and rule of five are rules of thumb in C++ for the building of exception-safe code and for formalizing rules on resource management. The rules prescribe how the default members of a class should be used to achieve these goals systematically.


1 Answers

The default destructor is fine, because the destructor of shared_ptr will take care of the deallocation of the object. The default copy constructor may be acceptable depending on your purposes: when you copy the object that owns the shared_ptr, the copy will share ownership with the original. The same would naturally be true of the default assignment operator. If that’s not what you want, define a copy constructor that does otherwise—for instance, that clones the referenced object.

like image 148
Jon Purdy Avatar answered Sep 20 '22 23:09

Jon Purdy