Create objects with auto p = std::make_unique<T>(args); from <memory>. The std::unique_ptr is the only owner and deletes the object when it goes out of scope, so you never write delete. Use std::make_shared<T>(args) only when several owners must keep the object alive together, and a std::weak_ptr to watch a shared object without keeping it alive.
A smart pointer is an object that owns something on the heap and deletes it in its own destructor. Because a destructor runs on every way out of a scope (the end of the block, a return, an exception), the memory can't leak and can't be freed twice. The standard library has three: std::unique_ptr for one owner, std::shared_ptr for several, and std::weak_ptr for a non-owning view of a shared object. The sections below cover each one, then the questions that come right after: how to pass them to functions, why make_shared beats new, how to break a reference cycle, custom deleters and arrays, and the mistakes that still crash programs that use smart pointers. Remember that the best pointer is often none at all: a plain member or a std::vector already cleans up after itself. Every example runs on this page: hit Run, then edit the code and run it again.
1std::unique_ptr and std::make_uniqueRecommended
std::unique_ptr is the default smart pointer. Exactly one unique_ptr owns the object, and when that owner is destroyed or reset, the object is deleted. std::make_unique<T>(args...) (C++14) builds the object and the pointer in one step, so no new appears in your code. A unique_ptr can't be copied, because two owners would both delete. It can be moved, which hands the object to a new owner and leaves the old one empty. Use -> and * as with a raw pointer, and test it in an if to see whether it holds anything.
#include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Connection { std::string name; explicit Connection(std::string n) : name(std::move(n)) { std::cout << "open " << name << '\n'; } ~Connection() { std::cout << "close " << name << '\n'; } }; int main() { { // make_unique allocates and wraps in one step: no new, no delete auto db = std::make_unique<Connection>("db"); std::cout << "using " << db->name << '\n'; } // db goes out of scope: the Connection is deleted here std::cout << "after the block\n"; auto a = std::make_unique<Connection>("cache"); // auto copy = a; // compile error: a unique_ptr cannot be copied auto b = std::move(a); // moving hands ownership over; a is now empty std::cout << "a is " << (a ? "set" : "null") << ", b owns " << b->name << '\n'; b.reset(); // delete now instead of at the end of main std::cout << "b is " << (b ? "set" : "null") << '\n'; // A vector of unique_ptr owns its elements: erase() and the // vector's own destruction delete them std::vector<std::unique_ptr<Connection>> pool; pool.push_back(std::make_unique<Connection>("w1")); pool.push_back(std::make_unique<Connection>("w2")); pool.push_back(std::make_unique<Connection>("w3")); pool.erase(pool.begin()); std::cout << "pool size " << pool.size() << '\n'; // No overhead: a unique_ptr is the size of a raw pointer std::cout << std::boolalpha << (sizeof(std::unique_ptr<int>) == sizeof(int*)) << '\n'; std::cout << "end of main\n"; } // pool goes away: w2 and w3 are closed
Output
The output traces each object's life. open db, using db and close db all print before after the block: the closing brace deleted it. After the move, the line reads a is null, b owns cache, and b.reset() prints close cache straight away. Erasing the first element of the vector deletes it (close w1, then pool size 2; more on erasing in removing an element from a vector). The sizeof check prints true: with the default deleter a unique_ptr is the size of a raw pointer, and its -> costs nothing extra. The last lines, close w2 and close w3, come after end of main, when the vector is destroyed. Uncomment auto copy = a; and the build stops with error: use of deleted function, naming the copy constructor of unique_ptr.
2std::shared_ptr and std::make_shared
A std::shared_ptr can be copied. Every copy is another owner, and they share a control block that counts them; the object is deleted when the last owner is destroyed or reset. use_count() reads that count (useful for learning and debugging; don't base logic on it in threaded code). Create one with std::make_shared<T>(args...), which allocates the object and the control block together, while std::shared_ptr<T>(new T) allocates them separately. The example replaces the global operator new with one that counts calls, to show that difference. A unique_ptr converts to a shared_ptr by moving it, so a factory that returns unique_ptr serves both kinds of caller.
#include <cstddef> #include <cstdlib> #include <iostream> #include <memory> #include <new> #include <string> #include <utility> // Count heap allocations, to compare make_shared with new below static int allocations = 0; void* operator new(std::size_t size) { ++allocations; if (void* p = std::malloc(size)) return p; throw std::bad_alloc(); } void operator delete(void* p) noexcept { std::free(p); } void operator delete(void* p, std::size_t) noexcept { std::free(p); } struct Texture { std::string file; explicit Texture(std::string f) : file(std::move(f)) { std::cout << "load " << file << '\n'; } ~Texture() { std::cout << "free " << file << '\n'; } }; int main() { auto grass = std::make_shared<Texture>("grass.png"); std::cout << "owners: " << grass.use_count() << '\n'; { auto copy = grass; // copying adds an owner std::cout << "owners: " << grass.use_count() << '\n'; } // copy is gone, the texture is not std::cout << "owners: " << grass.use_count() << '\n'; auto other = grass; grass.reset(); // one owner left: nothing is freed yet std::cout << "grass reset, other owns " << other->file << '\n'; other.reset(); // the last owner lets go: the texture is freed now std::cout << "other reset\n"; // A unique_ptr converts to a shared_ptr (by move), never the reverse auto solo = std::make_unique<Texture>("sky.png"); std::shared_ptr<Texture> sky = std::move(solo); std::cout << "solo is " << (solo ? "set" : "null") << ", sky owners: " << sky.use_count() << '\n'; // make_shared puts the object and its control block in one allocation int before = allocations; auto one = std::make_shared<long>(1); int made = allocations - before; before = allocations; std::shared_ptr<long> two(new long(2)); int newed = allocations - before; std::cout << "make_shared: " << made << ", shared_ptr(new): " << newed << '\n'; std::cout << "sizeof shared_ptr: " << sizeof(std::shared_ptr<long>) << ", raw pointer: " << sizeof(long*) << '\n'; }
Output
The count goes owners: 1, owners: 2 while the copy lives, then back to owners: 1. Resetting grass frees nothing because other still owns the texture (grass reset, other owns grass.png); free grass.png prints only when other lets go. The moved unique_ptr is empty and the new shared_ptr is the only owner: solo is null, sky owners: 1. The counter prints make_shared: 1, shared_ptr(new): 2, one allocation against two. A shared_ptr is twice the size of a raw pointer here (sizeof shared_ptr: 16, raw pointer: 8): one pointer to the object, one to the control block, and every copy and destruction updates the count atomically. That is why unique_ptr stays the default. One cost of make_shared: since the object and the control block share one allocation, a weak_ptr that outlives the last owner keeps the whole block allocated, object memory included (the destructor still runs on time). For a large object watched by long-lived weak_ptrs, or when you need a custom deleter, use std::shared_ptr<T>(new T) instead.
3Passing smart pointers to functions
The parameter type says what the function does with ownership, and most functions do nothing with it. If a function only uses the object, take T& or const T& (or T* when "no object" is allowed) and call it with *p or p.get(): it then works with any owner, smart or not, and copies nothing. Take a std::unique_ptr<T> by value only when the function takes ownership; the caller has to write std::move(p), which makes the hand-over visible. A factory returns std::unique_ptr<T> by value. For shared_ptr, take it by value when the function keeps a copy (and move it into place), and by const& when it might. This is the C++ Core Guidelines advice (rules R.30 to R.37).
#include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Job { std::string name; explicit Job(std::string n) : name(std::move(n)) {} ~Job() { std::cout << " ~Job " << name << '\n'; } }; // 1. The function only uses the object: take a reference (or a pointer // if "no object" is allowed). It works with any owner, smart or not. void print(const Job& job) { std::cout << "print " << job.name << '\n'; } void print_if(const Job* job) { std::cout << (job ? job->name : "no job") << '\n'; } // 2. The function takes ownership: unique_ptr by value, caller moves in void run_and_finish(std::unique_ptr<Job> job) { std::cout << "running " << job->name << '\n'; } // job is deleted here // 3. A factory returns ownership: return the unique_ptr by value std::unique_ptr<Job> make_job(const std::string& name) { return std::make_unique<Job>(name); // no std::move needed on return } // 4. shared_ptr by value is a copy: one more owner while the call runs void by_value(std::shared_ptr<Job> job) { std::cout << "by value, owners: " << job.use_count() << '\n'; } void by_ref(const std::shared_ptr<Job>& job) { std::cout << "by const&, owners: " << job.use_count() << '\n'; } // 5. A function that keeps a copy: take by value and move it into place struct Queue { std::vector<std::shared_ptr<Job>> jobs; void add(std::shared_ptr<Job> job) { jobs.push_back(std::move(job)); } }; int main() { auto build = make_job("build"); print(*build); // pass the object, not the smart pointer print_if(build.get()); // get() gives a non-owning raw pointer print_if(nullptr); run_and_finish(std::move(build)); // ownership moves into the call std::cout << "build is " << (build ? "set" : "null") << '\n'; auto deploy = std::make_shared<Job>("deploy"); by_value(deploy); by_ref(deploy); Queue queue; queue.add(deploy); // copies: the queue and main both own it std::cout << "after add, owners: " << deploy.use_count() << '\n'; std::cout << "end of main\n"; }
Output
print and print_if never see a smart pointer, so they print print build, build and no job without touching ownership. run_and_finish owns the job once it is called, so ~Job build prints at the end of that function, and back in main the pointer is empty (build is null). Passing a shared_ptr by value made a copy for the call: by value, owners: 2. By const& it stayed at by const&, owners: 1. Queue::add keeps the job, so after the call main and the queue both own it (after add, owners: 2); a caller that no longer needs its copy can write queue.add(std::move(deploy)) and skip the count update entirely. Two rarer forms: std::unique_ptr<T>& for a function that may replace the caller's object, and const std::unique_ptr<T>&, which says nothing a const T* wouldn't.
4std::weak_ptr: break cycles and observe
Reference counting has one blind spot: a cycle. If two objects hold shared_ptrs to each other, each keeps the other's count above zero, so neither is ever deleted. A std::weak_ptr points at an object managed by shared_ptr without counting as an owner. Use it for back-pointers (a child pointing at its parent), caches, and observers that must not keep their subject alive. You can't use a weak_ptr directly: lock() returns a shared_ptr that keeps the object alive while you use it, or an empty one if the object is gone.
#include <iostream> #include <memory> #include <string> #include <utility> #include <vector> // A cycle of shared_ptr: each keeps the other alive forever struct Leaky { std::shared_ptr<Leaky> other; ~Leaky() { std::cout << "~Leaky\n"; } // never printed }; struct Team; struct Player { std::string name; std::weak_ptr<Team> team; // observes the team, does not own it explicit Player(std::string n) : name(std::move(n)) {} ~Player() { std::cout << "~Player " << name << '\n'; } }; struct Team { std::string name; std::vector<std::shared_ptr<Player>> players; // owns its players explicit Team(std::string n) : name(std::move(n)) {} ~Team() { std::cout << "~Team " << name << '\n'; } }; void show_team(const Player& p) { // lock() returns a shared_ptr: empty if the team is already gone if (auto team = p.team.lock()) { std::cout << p.name << " plays for " << team->name << '\n'; } else { std::cout << p.name << " has no team\n"; } } int main() { { auto a = std::make_shared<Leaky>(); auto b = std::make_shared<Leaky>(); a->other = b; b->other = a; std::cout << "cycle owners: " << a.use_count() << '\n'; } // a and b go out of scope, but each object still owns the other std::cout << "leaked: no ~Leaky above\n"; auto ana = std::make_shared<Player>("Ana"); { auto team = std::make_shared<Team>("Robots"); team->players.push_back(ana); ana->team = team; // a weak_ptr does not add an owner std::cout << "team owners: " << team.use_count() << '\n'; show_team(*ana); } // the team is destroyed: nothing kept it alive std::cout << std::boolalpha << "expired: " << ana->team.expired() << '\n'; show_team(*ana); }
Output
The first block prints cycle owners: 2 and then no ~Leaky at all: when a and b went out of scope each count dropped to 1, not 0, so both objects leaked. The team version has the owning pointer going one way and a weak_ptr going back, so the team has a single owner (team owners: 1). While it lives, lock() succeeds and prints Ana plays for Robots. At the closing brace, ~Team Robots runs; the player survives because main still owns ana. Then expired: true and Ana has no team. Prefer lock() over expired() before use: in threaded code the object can disappear between an expired() check and the next line, while the shared_ptr from lock() holds it for as long as you need it.
5Custom deleters and arrays
A smart pointer can own more than newed memory. Give unique_ptr a deleter type as its second template argument and it calls that instead of delete: a FILE* gets fclose, a C library handle gets its free function. Many answers write decltype(&std::fclose) for the type; since C++20 the standard no longer promises you can take the address of most standard library functions, and a function pointer adds 8 bytes, so a small struct is the better deleter. For arrays, the T[] forms such as make_unique<int[]>(n) call delete[] and give you [] indexing. shared_ptr takes its deleter as a constructor argument, so it doesn't change the pointer's type.
#include <cstdio> #include <iostream> #include <memory> // A stateless deleter type: closes the FILE and says so struct FileCloser { void operator()(std::FILE* f) const { std::fclose(f); std::cout << "file closed\n"; } }; using FilePtr = std::unique_ptr<std::FILE, FileCloser>; int main() { { // The deleter runs instead of delete when the owner goes away FilePtr out(std::fopen("notes.txt", "w")); if (!out) return 1; std::fputs("smart pointers own files too\n", out.get()); } // fclose runs here, so the text is flushed to disk FilePtr in(std::fopen("notes.txt", "r")); char line[64]; if (in && std::fgets(line, sizeof line, in.get())) std::cout << line; in.reset(); // A function pointer as the deleter works, but it is stored in the // unique_ptr; an empty deleter type adds no size std::cout << "with FileCloser: " << sizeof(FilePtr) << " bytes\n"; std::cout << "with a function pointer: " << sizeof(std::unique_ptr<std::FILE, int (*)(std::FILE*)>) << " bytes\n"; // Arrays: the [] form calls delete[]; make_unique<T[]> zero-fills auto numbers = std::make_unique<int[]>(5); numbers[2] = 42; for (int i = 0; i < 5; ++i) std::cout << (i ? " " : "") << numbers[i]; std::cout << '\n'; // shared_ptr<T[]> (C++17) and make_shared<T[]> (C++20) std::shared_ptr<double[]> samples = std::make_shared<double[]>(3, 0.5); std::cout << samples[0] + samples[1] + samples[2] << '\n'; // shared_ptr takes the deleter in the constructor, not the type std::shared_ptr<int> traced(new int(7), [](int* p) { std::cout << "deleting " << *p << '\n'; delete p; }); std::cout << "end of main\n"; }
Output
file closed prints at the closing brace, before the file is read back, so the text was on disk when the second FilePtr opened it (smart pointers own files too, then file closed from in.reset()). The empty deleter struct keeps the pointer at with FileCloser: 8 bytes, while with a function pointer: 16 bytes stores the pointer in every unique_ptr. make_unique<int[]>(5) value-initializes the elements, so the array prints 0 0 42 0 0, and the make_shared array of three 0.5s sums to 1.5. The lambda deleter runs last: deleting 7 after end of main. For reading files you don't need any of this, because std::ifstream already closes itself (see reading a file line by line), and for a growable array std::vector beats unique_ptr<T[]>.
6shared_from_this and other mistakes
Smart pointers remove most memory bugs, but a few patterns still give you a double delete or a dangling pointer. The big one: never create two owners from the same raw pointer. Writing std::shared_ptr<T>(p.get()) or std::shared_ptr<T>(this) starts a second control block, and both will delete the object. That is undefined behaviour, so it isn't run here. When a member function needs a shared_ptr to its own object, inherit from std::enable_shared_from_this<T> and call shared_from_this(), or weak_from_this() (C++17) for a callback that must not keep the object alive.
#include <functional> #include <iostream> #include <memory> #include <string> #include <utility> struct Session : std::enable_shared_from_this<Session> { std::string id; explicit Session(std::string i) : id(std::move(i)) {} ~Session() { std::cout << "~Session " << id << '\n'; } // A shared_ptr to *this that joins the existing owners. // Never write std::shared_ptr<Session>(this): that starts a second // count, and the object would be deleted twice. std::shared_ptr<Session> self() { return shared_from_this(); } // A callback that must not keep the session alive: capture a weak_ptr std::function<void()> on_timeout() { return [weak = weak_from_this()] { if (auto s = weak.lock()) std::cout << "timeout for " << s->id << '\n'; else std::cout << "session already closed\n"; }; } }; int main() { auto s1 = std::make_shared<Session>("s1"); auto same = s1->self(); std::cout << "owners: " << s1.use_count() << '\n'; // The same rule for any shared_ptr: copy it, never wrap .get() again. // std::shared_ptr<Session> twin(s1.get()); // double delete at exit // shared_from_this() needs an existing shared_ptr owner Session on_stack("s2"); try { on_stack.self(); } catch (const std::bad_weak_ptr& e) { std::cout << "error: " << e.what() << '\n'; } auto callback = s1->on_timeout(); callback(); same.reset(); s1.reset(); // last owner: s1 is destroyed even though callback exists callback(); // release() gives up ownership without deleting: you must delete it auto number = std::make_unique<int>(5); int* raw = number.release(); std::cout << "after release: " << (number ? "set" : "null") << ", value " << *raw << '\n'; delete raw; }
Output
shared_from_this() joined the existing owners: owners: 2, not two separate counts of 1. Calling it on an object that no shared_ptr owns throws std::bad_weak_ptr (since C++17), caught here as error: bad_weak_ptr. The callback captured a weak_ptr, so it prints timeout for s1 while the session lives, does not stop ~Session s1 when the owners reset, and afterwards prints session already closed. Capturing shared_from_this() instead would keep the session alive as long as the callback exists. release() hands back the raw pointer and empties the unique_ptr (after release: null, value 5), so the delete is yours again; use reset() when you want the object gone. Finally, a raw pointer from get() is only a view: it dangles as soon as the last owner lets go.
7Which should you use?
| Tool | Owners | Cost | Use it for |
|---|---|---|---|
| std::make_unique<T>() | One | Same as a raw pointer | The default for any object you would new |
| T& / const T& / T* parameter | None (borrows) | Free | Functions that only use the object |
| std::make_shared<T>() | Many | 16 bytes, atomic count | Objects with no single owner |
| std::weak_ptr<T> | None (observes) | lock() per use | Back-pointers, caches, callbacks |
| std::unique_ptr<T, Deleter> | One | Free with an empty deleter | FILE*, C library handles |
| std::make_unique<T[]>(n) | One | Fixed size | Buffers for C APIs; prefer std::vector |
| new / delete | You, by hand | Leaks on early return or exception | Avoid in new code |
Frequently asked questions
What is a smart pointer in C++ and when should I use one?
A smart pointer is a class template from <memory> that owns a heap object and deletes it in its destructor, so the object is freed on every path out of the scope, exceptions included. Use one whenever you would otherwise write new: std::unique_ptr (via std::make_unique) by default, std::shared_ptr (via std::make_shared) only when ownership is really shared, and std::weak_ptr to observe a shared object. Don't use one when a plain value, a member or a container such as std::vector would do; those clean up after themselves too.
Should I pass a shared_ptr by value or by const reference?
If the function only uses the object, pass neither: take const T& or T* and call it with *p or p.get(). If the function stores a copy, take std::shared_ptr<T> by value and std::move it into the member; a caller that is done with its pointer can move it in and avoid touching the count. Use const std::shared_ptr<T>& when the function might take a copy, for example only on some paths. Passing by value costs an atomic increment and decrement per call, which the example shows as by value, owners: 2 against by const&, owners: 1.
How do I pass a unique_ptr to a function?
Decide whether the function takes ownership. If it does, declare the parameter as std::unique_ptr<T> by value and call it with f(std::move(p)); afterwards p is empty. If it only uses the object, declare T&, const T& or T* and call f(*p) or f(p.get()). Use std::unique_ptr<T>& only when the function may reset or replace the caller's object. A plain f(p) with a by-value parameter does not compile, because a unique_ptr cannot be copied.
Why use make_shared instead of shared_ptr<T>(new T)?
std::make_shared<T>(args) allocates the object and the control block in one go, while std::shared_ptr<T>(new T(args)) makes two allocations; the counting example prints make_shared: 1, shared_ptr(new): 2. It also keeps the object and its count close together in memory and keeps new out of your code. Before C++17 it also avoided a leak in calls like f(std::shared_ptr<T>(new T), g()) when g() throws. Use the new form when you need a custom deleter, or when long-lived weak_ptrs would otherwise keep a large object's memory allocated.
Is std::shared_ptr thread-safe?
The reference count is: different threads can copy and destroy their own shared_ptrs to the same object, and the object is deleted exactly once. The object itself is not protected, so reading and writing it from several threads still needs a mutex or atomics. One shared_ptr variable that one thread reassigns while another reads it is also a data race; use std::atomic<std::shared_ptr<T>> (C++20) for that.
What happened to std::auto_ptr?
std::auto_ptr was deprecated in C++11 and removed in C++17. It "copied" by silently moving ownership, which broke containers and algorithms; std::unique_ptr replaced it with an explicit std::move. GCC's library still ships it, so on this compiler std::auto_ptr<int> compiles in C++20 mode, with warning: 'template<class> class std::auto_ptr' is deprecated: use 'std::unique_ptr' instead. libc++ (Clang) and MSVC drop it in C++17 mode, so replace it with std::unique_ptr.