WeCodeAcademy

C++ Smart Pointers

Raw new/delete is easy to get wrong. Smart pointers free memory automatically: unique_ptr has one owner, shared_ptr counts owners.

ExampleC++
#include <iostream>
#include <memory>
using namespace std;

struct Resource {
  string name;
  Resource(string n) : name(n) { cout << "create " << name << endl; }
  ~Resource() { cout << "destroy " << name << endl; }
};

int main() {
  {
    unique_ptr<Resource> a = make_unique<Resource>("A");
    cout << "using " << a->name << endl;
  }  // a is destroyed here
  cout << "after block" << endl;

  shared_ptr<Resource> b = make_shared<Resource>("B");
  {
    shared_ptr<Resource> c = b;
    cout << "owners: " << b.use_count() << endl;
  }
  cout << "owners: " << b.use_count() << endl;
  return 0;
}
Output
create A
using A
destroy A
after block
create B
owners: 2
owners: 1
destroy B

The destructor runs exactly when the last owner goes away. This pattern is called RAII: resources are tied to object lifetimes.

Quick check

How many owners can a unique_ptr have?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.