Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Smart Pointers in C++

Manage memory automatically in C++ with unique_ptr and shared_ptr. See ownership move, reference counting with use_count, and when each object dies.

IntermediateMemory Management ProgramsExample 11 of 11
smart-pointers.cpp
1#include <iostream>
2#include <memory>
3using namespace std;
4
5class MyClass {
6private:
7 int value;
8
9public:
10 MyClass(int v) : value(v) {
11 cout << "MyClass object created with value: " << value << endl;
12 }
13
14 void display() {
15 cout << "Value: " << value << endl;
16 }
17
18 ~MyClass() {
19 cout << "MyClass object destroyed (value: " << value << ")" << endl;
20 }
21};
22
23int main() {
24 cout << "=== unique_ptr ===" << endl;
25 {
26 // unique_ptr - exclusive ownership
27 unique_ptr<MyClass> ptr1 = make_unique<MyClass>(10);
28 ptr1->display();
29
30 // Cannot copy, but can move
31 unique_ptr<MyClass> ptr2 = move(ptr1);
32 if (ptr1 == nullptr) {
33 cout << "ptr1 is now null (ownership transferred)" << endl;
34 }
35 ptr2->display();
36 } // Automatically deleted
37
38 cout << "\n=== shared_ptr ===" << endl;
39 {
40 // shared_ptr - shared ownership
41 shared_ptr<MyClass> ptr1 = make_shared<MyClass>(20);
42 cout << "Reference count: " << ptr1.use_count() << endl;
43
44 {
45 shared_ptr<MyClass> ptr2 = ptr1; // Share ownership
46 cout << "Reference count: " << ptr1.use_count() << endl;
47 ptr2->display();
48 } // ptr2 goes out of scope
49
50 cout << "Reference count: " << ptr1.use_count() << endl;
51 ptr1->display();
52 } // Automatically deleted when count reaches 0
53
54 cout << "\nAll objects automatically destroyed" << endl;
55
56 return 0;
57}

Sample Output

ptr1 is now null (ownership transferred)

After move(ptr1).

Reference count: 2

ptr1 and ptr2 share ownership.

MyClass object destroyed (value: 20)

The last shared_ptr went away.

In this one

  • How unique_ptr gives single, movable ownership
  • Why unique_ptr cannot be copied
  • How shared_ptr counts owners with use_count
  • When objects are destroyed and why weak_ptr exists

How it works

  1. 1

    make_unique creates value 10; ptr1 owns it.

  2. 2

    move(ptr1) transfers ownership to ptr2; ptr1 becomes null.

  3. 3

    Leaving the block destroys the object.

  4. 4

    make_shared creates value 20 with count 1; copying raises it to 2.

  5. 5

    Counts drop back as owners leave; the object dies at 0.

Edge cases

Copying a unique_ptr

Write unique_ptr<MyClass> p2 = ptr1;

It does not compile, because unique_ptr's copy constructor is deleted. Use move to transfer ownership.

Using a moved-from unique_ptr

Call ptr1->display() after move.

ptr1 is null, so this is a null dereference and undefined behavior.

What's going on

Smart pointers are classes that hold a pointer and delete it for you. They put RAII into the standard library, so you rarely need a bare delete in modern C++. This program shows the two main ones.

unique_ptr means one owner. make_unique<MyClass>(10) creates the object (and needs C++14). ptr1->display() works like a normal pointer. You cannot copy a unique_ptr, because two owners would both try to delete. You can move it: unique_ptr<MyClass> ptr2 = move(ptr1); hands ownership to ptr2 and leaves ptr1 empty, which the null check confirms. At the closing brace, ptr2 is destroyed and deletes the object, printing "MyClass object destroyed (value: 10)".

shared_ptr means shared ownership with a reference count, which is the number of shared_ptrs currently owning the object. make_shared<MyClass>(20) starts the count at 1. Copying it into ptr2 raises the count to 2. When the inner block ends, ptr2 is destroyed and the count drops back to 1. Only when the last owner, ptr1, goes away does the count reach 0 and the object get deleted.

Which to use: unique_ptr by default. It costs nothing extra over a raw pointer. Use shared_ptr only when several parts of the program truly need to keep the same object alive.

One trap with shared_ptr: if two objects hold shared_ptrs to each other, the counts never reach 0 and both leak. weak_ptr breaks such cycles by watching without owning.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <memory> is there because it provides smart pointer classes (unique_ptr, shared_ptr). Leave one out and the compiler stops at the first name it does not recognize.

Understanding Smart Pointers

Smart Pointer Concept:

Automatically manage memory
Delete objects when no longer needed
Prevent memory leaks
Safer than raw pointers

Types:

unique_ptr: exclusive ownership
shared_ptr: shared ownership
weak_ptr: non-owning reference

unique_ptr - Exclusive Ownership

Basic Usage:

unique_ptr<int> ptr = make_unique<int>(10);

What happens here:

Only one unique_ptr can own object
Automatically deleted when unique_ptr destroyed
Cannot be copied (only moved)
Exclusive ownership model

Automatic Cleanup:

{

unique_ptr<int> ptr = make_unique<int>(10);

// Use ptr

} // ptr automatically deleted here

shared_ptr - Shared Ownership

Basic Usage:

shared_ptr<int> ptr1 = make_shared<int>(10);

shared_ptr<int> ptr2 = ptr1; // Share ownership

What happens here:

Multiple shared_ptr can own same object
Reference counting tracks owners
Deleted when last shared_ptr destroyed
Shared ownership model

Reference Counting:

Each shared_ptr increments count
When shared_ptr destroyed, count decrements
Object deleted when count reaches 0

When to Use Smart Pointers

Good fits:

Automatic memory management
Preventing memory leaks
Modern C++ code (C++11+)
Replacing raw pointers
Exception-safe code

Example Scenarios:

Dynamic object creation
Resource management
Container of pointers
Polymorphism with base pointers
Any dynamic memory allocation

Advantages Over Raw Pointers

Automatic Cleanup:

No need for manual delete
Automatically freed when out of scope
Exception-safe (freed even if exception occurs)

Memory Safety:

Prevents memory leaks
Prevents double deletion
Prevents dangling pointers

Modern C++:

Preferred over raw pointers
Part of standard library
Type-safe and efficient

Important Considerations

unique_ptr:

Exclusive ownership
Cannot be copied
Can be moved (transfer ownership)
Lightweight (no overhead)

shared_ptr:

Shared ownership
Can be copied
Reference counting overhead
Thread-safe reference counting

Performance:

unique_ptr: no overhead
shared_ptr: slight overhead (reference counting)
Usually negligible for most applications

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does ptr1.use_count() print right after shared_ptr<MyClass> ptr2 = ptr1;?

Pick an answer to check it.

Question 2

Why can a unique_ptr be moved but not copied?

Pick an answer to check it.

Questions people ask

Does unique_ptr have overhead?

Practically none compared with a raw pointer.

Why make_shared instead of shared_ptr(new T)?

It does one allocation for the object and the count together, and is exception-safe.

What is weak_ptr?

A non-owning observer of a shared_ptr object, used to break reference cycles.