C++ Smart Pointers
In the Memory Management lesson you saw how easy it is to leak memory or delete it twice with raw new and delete. Smart pointers, defined in <memory>, solve this. They are objects that own a heap-allocated object and automatically delete it when it is no longer needed. In modern C++ you should almost never write delete yourself.
| Smart pointer | Ownership | Copyable? | Use when |
|---|---|---|---|
std::unique_ptr<T> |
exactly one owner | no (only movable) | the default choice |
std::shared_ptr<T> |
many owners, reference counted | yes | ownership is genuinely shared |
std::weak_ptr<T> |
no ownership, observes a shared_ptr |
yes | breaking cycles, caches |
unique_ptr
A unique_ptr is the sole owner of its object. When the unique_ptr is destroyed, so is the object. Create one with std::make_unique:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
struct Robot {
string name;
explicit Robot(string n) : name(n) { cout << "build " << name << "\n"; }
~Robot() { cout << "scrap " << name << "\n"; }
void wave() const { cout << name << " waves\n"; }
};
int main() {
{
unique_ptr<Robot> r = make_unique<Robot>("R2");
r->wave(); // use like a raw pointer
(*r).wave();
cout << "leaving scope\n";
} // Robot deleted automatically here
cout << "after scope\n";
}build R2
R2 waves
R2 waves
leaving scope
scrap R2
after scope
Transferring ownership with std::move
A unique_ptr cannot be copied — there would be two owners. But ownership can be moved, which leaves the source empty (null):
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
unique_ptr<int> makeCounter(int start) {
return make_unique<int>(start); // returning moves automatically
}
void consume(unique_ptr<int> p) { // takes ownership
cout << "consumed " << *p << "\n";
} // freed here
int main() {
unique_ptr<int> a = makeCounter(5);
// unique_ptr<int> b = a; // error: copy is deleted
unique_ptr<int> b = move(a); // ownership moves to b
cout << boolalpha << "a empty? " << (a == nullptr) << ", *b = " << *b << "\n";
consume(move(b));
cout << "b empty? " << (b == nullptr) << "\n";
vector<unique_ptr<int>> owners;
owners.push_back(make_unique<int>(1));
owners.push_back(make_unique<int>(2));
cout << "vector owns " << owners.size() << " ints, sum "
<< *owners[0] + *owners[1] << "\n";
}a empty? true, *b = 5
consumed 5
b empty? true
vector owns 2 ints, sum 3
shared_ptr
A shared_ptr keeps a reference count: how many shared_ptrs currently own the object. Copying increases it, destroying decreases it, and the object is deleted when the count reaches zero:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
struct Texture {
string file;
explicit Texture(string f) : file(f) { cout << "load " << file << "\n"; }
~Texture() { cout << "unload " << file << "\n"; }
};
struct Sprite {
shared_ptr<Texture> tex;
};
int main() {
auto grass = make_shared<Texture>("grass.png");
cout << "count: " << grass.use_count() << "\n";
{
Sprite s1{grass}, s2{grass};
cout << "count with two sprites: " << grass.use_count() << "\n";
}
cout << "count after sprites gone: " << grass.use_count() << "\n";
grass.reset(); // drop the last owner
cout << "end of main\n";
}load grass.png
count: 1
count with two sprites: 3
count after sprites gone: 1
unload grass.png
end of main
Note: Reference counting has a cost (an extra allocation and atomic counter updates), so don't use
shared_ptrjust to avoid thinking about ownership. Start withunique_ptrand switch only when sharing is real.
weak_ptr and reference cycles
If two objects hold shared_ptrs to each other, their counts never reach zero and they leak. A weak_ptr observes an object without owning it. To use it, call lock(), which returns a shared_ptr (empty if the object is gone):
#include <iostream>
#include <memory>
#include <string>
using namespace std;
struct Person {
string name;
weak_ptr<Person> friendOf; // weak: does not keep the friend alive
explicit Person(string n) : name(n) {}
~Person() { cout << name << " destroyed\n"; }
};
int main() {
auto ann = make_shared<Person>("Ann");
weak_ptr<Person> watcher;
{
auto bob = make_shared<Person>("Bob");
ann->friendOf = bob;
bob->friendOf = ann; // a cycle, but made of weak pointers
watcher = bob;
if (auto f = ann->friendOf.lock()) {
cout << "Ann's friend is " << f->name << "\n";
}
}
cout << boolalpha << "Bob still alive? " << !watcher.expired() << "\n";
}Ann's friend is Bob
Bob destroyed
Bob still alive? false
Ann destroyed
Guidelines
- Use
make_unique/make_sharedinstead ofnew— they are safer and shorter. - Functions that only use an object should take a plain reference (
const Robot&) or raw pointer, not a smart pointer. Pass smart pointers only when transferring or sharing ownership. - A raw pointer in modern code should mean "I am looking at this, I don't own it".
Test yourself
Why can't a unique_ptr be copied?
- It is too large
- A copy would create two owners of the same object
- It has no copy syntax in C++
- It can be copied with
=
When is the object owned by shared_ptrs deleted?
- When the first owner is destroyed
- When the use count drops to zero
- At the end of main
- Never automatically
What problem does weak_ptr mainly solve?
- Slow allocation
- Reference cycles between shared_ptrs
- Thread safety
- Array allocation