C++ Programming: Objects, RAII and the STL · Memory and Ownership

Smart Pointers: unique_ptr and shared_ptr

Smart pointers delete heap objects for you. unique_ptr has one owner; shared_ptr counts its owners.

smart_pointers.cpp

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

struct Song {
    int plays;
    Song(int p) : plays(p) {}
    ~Song() { cout << "song freed" << endl; }
};

int main() {
    unique_ptr<Song> mine = make_unique<Song>(1);   // the only owner
    mine->plays++;
    unique_ptr<Song> moved = move(mine);            // ownership moves; mine is now empty
    bool mineEmpty = (mine == nullptr);

    shared_ptr<int> a = make_shared<int>(7);
    shared_ptr<int> b = a;                          // two owners of one int
    long owners = a.use_count();
    cout << moved->plays << " " << mineEmpty << " " << owners << endl;
    return 0;                                       // the Song is freed automatically
}

Step by step

  1. make_unique creates a Song on the heap owned by mine.
  2. plays in the Song that mine points to changes from 1 to 2.
  3. move hands ownership to moved; mine becomes empty.
  4. mineEmpty is created on the stack with the value true.
  5. a is created on the stack with the value → 7 (1 owners).
  6. b shares the same int: two owners.
  7. use_count is 2.
  8. It prints 2 1 2.
  9. The method returns 0.
  10. 2 1 2, then "song freed" as moved goes out of scope.