C++ Programming: Objects, RAII and the STL · Memory and Ownership
Smart pointers delete heap objects for you. unique_ptr has one owner; shared_ptr counts its owners.
#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
}plays in the Song that mine points to changes from 1 to 2.mineEmpty is created on the stack with the value true.a is created on the stack with the value → 7 (1 owners).2 1 2.0.