AnyCompiler

Smart Pointers

A unique_ptr owns a heap-allocated object exclusively — when it goes out of scope, its destructor automatically deletes the object it owns, leaning directly on the RAII pattern from earlier in this course. make_unique creates one without ever writing new or delete by hand.

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

class Resource {
public:
    Resource() { cout << "Resource acquired" << endl; }
    ~Resource() { cout << "Resource released" << endl; }
    void use() { cout << "Using resource" << endl; }
};

int main() {
    unique_ptr<Resource> res = make_unique<Resource>();
    res->use();
    return 0;
}
Output
Resource acquired
Using resource
Resource released

shared_ptr

A shared_ptr allows multiple owners of the same object, tracking how many shared_ptrs currently point at it with a reference count. The object is only destroyed once that count drops to zero — useful when a single, clear owner genuinely isn't possible.

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

int main() {
    shared_ptr<int> a = make_shared<int>(42);
    shared_ptr<int> b = a;
    cout << "value = " << *a << endl;
    cout << "use_count = " << a.use_count() << endl;
    return 0;
}
Output
value = 42
use_count = 2

Modern C++ code reaches for unique_ptr and shared_ptr by default, and treats raw new/delete as a last resort — smart pointers give you the same deterministic cleanup as any other RAII type, without a programmer having to remember to call delete manually.

Next: exceptions and error handling — try, catch, and throw.

Practice exercise

Use make_unique to create a unique_ptr<int> holding the value 99, then print the value it points to.