Using shared_ptr, a short article

How can I create a shared_ptr?

// Example 1 - you can see that you construct a new shared_ptr with a pointer
// to my_class
std::shared_ptr<my_class> example1 = std::shared_ptr<my_class>(new my_class());

// Example 2 - you can also use the convenience function make_shared to make
// it easier to type
std::shared_ptr<my_class> example2 = std::make_shared<my_class>();

// Example 3 - and if you really want to go full blown modern, use auto so
// that you don't have to type the type for the variable declaration
auto example3 = std::make_shared<my_class>();

How about a NULL shared_ptr?

std::shared_ptr<my_class> my_nullptr;
auto my_nullptr = std::shared_ptr<my_class>();

What if I already have a shared_ptr, that I own, and I want to null it out?

auto my_ptr = std::make_shared<my_class>();

// Let's pretend to do some stuff

Ok, ok. What if I want to null out my shared_ptr and at the same time, replace it with a new instance?

auto my_ptr = std::make_shared<my_class>();

// Let's pretend to do some stuff; let's reset it with a new instance
my_ptr.reset(new my_class());

How do I check if the shared_ptr is still in use?

auto my_ptr = std::make_shared<my_class>();

// More pretending ...
printf("Reference count: %ld\n", my_ptr.use_count();

What if I’m in a class function and want to take my current instance and pass it to another function as a shared_ptr?
A: So long as your class is already managed by an existing shared_ptr, you can:

// Add this at the class declaration:
class my_class : public std::enable_shared_from_this<my_class>

// And add this member function
std::shared_ptr<my_class> get_shared_ptr()
return shared_from_this();

That’s pretty much it. Just remember that you need the public keyword before std::enable_shared_from_this, otherwise you would get some weird behavior when you call get_shared_ptr.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.