Using shared_ptr

While unique_ptr is meant for single-owner scenarios, shared_ptr is the reference counted smart pointer class that allows you to share the smart pointer around your code. Consider the code snippet below, which uses the NumberStore example from the previous blog entry.

void SharedPtrVersion()
  shared_ptr<NumberStore> number(
      new NumberStore(100)); // Ref Count : 1
  Foo(number); // Ref Count : 1 on function return
  shared_ptr<NumberStore> copy = number; // Ref Count : 2
  Foo(number); // Ref Count : 2 on function return
  copy.reset(); // Ref Count : 1
  Foo(number); // Ref Count : 1 on function return
  Foo(copy); // This will crash

The output will be:

NumberStore ctor
Foo : 100 Ref Count : 2
Foo : 100 Ref Count : 3
Foo : 100 Ref Count : 2
NumberStore dtor

The ref count goes up inside Foo‘s body as Foo has received a copy of the shared_ptr. It goes back as soon as Foo returns. Creating a copy increments the ref count as expected. Calling reset() decrements the ref count and releases ownership. Trying to pass around a reset shared_ptr will give you a crash / access violation.

The shared_ptr class also allows you to pass a lambda as the deletion method called in the destructor, so you can do something like this.

void SharedPtrArrayVersion()
  shared_ptr<NumberStore> number(
    new NumberStore[3], 
    [](NumberStore* pNumStore) { delete[] pNumStore; });

Note: when you call reset, if the ref count drops to 0, the object is destroyed. Example:

void SharedPtrVersion2()
  shared_ptr<NumberStore> number(new NumberStore(100));
  shared_ptr<NumberStore> copy = number;
  copy.reset(); // destructor is called here
  cout << "end of method" << endl;

The next blog entry will talk about the weak_ptr class (the last of the 3 smart pointers introduced in C++ 11).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s