C++ Smart Pointers

Smart pointers in C++ are objects that manage the lifetime of dynamically allocated memory automatically. They help prevent memory leaks by ensuring that memory is properly deallocated when it is no longer needed. Smart pointers are part of the <memory> header in C++11 and later.

Types of Smart Pointers

  • Smart pointers automatically manage memory, reducing memory leaks and dangling pointers.
  • unique_ptr provides exclusive ownership; use std::move to transfer ownership.
  • shared_ptr allows multiple owners and keeps a reference count.
  • weak_ptr is used to break circular references and does not affect reference count.

Next Topic

Next, learn about Lambda Expressions in C++.

  • std::unique_ptr: Owns the object exclusively. Cannot be copied, only moved. Automatically deletes the object when it goes out of scope.
  • std::shared_ptr: Multiple shared pointers can point to the same object. The object is deleted when the last shared pointer is destroyed.
  • std::weak_ptr: Works with shared_ptr to prevent circular references. It does not affect the reference count and cannot directly access the object.

Example: Unique Pointer

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

class Test {
public:
    Test() { cout << "Constructor called" << endl; }
    ~Test() { cout << "Destructor called" << endl; }
    void display() { cout << "Hello from Test" << endl; }
};

int main() {
    unique_ptr<Test> ptr1 = make_unique<Test>(); // Create unique_ptr
    ptr1->display();

    // unique_ptr automatically deletes the object when going out of scope
    return 0;
}

Output

Constructor called
Hello from Test
Destructor called

Example: Shared Pointer

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

class Test {
public:
    Test() { cout << "Constructor called" << endl; }
    ~Test() { cout << "Destructor called" << endl; }
};

int main() {
    shared_ptr<Test> ptr1 = make_shared<Test>();
    shared_ptr<Test> ptr2 = ptr1; // Shared ownership

    cout << "Use count: " << ptr1.use_count() << endl;

    // Object is destroyed automatically when last shared_ptr goes out of scope
    return 0;
}

Output

Constructor called
Use count: 2
Destructor called

Important Notes

  • Smart pointers automatically manage memory, reducing memory leaks and dangling pointers.
  • unique_ptr provides exclusive ownership; use std::move to transfer ownership.
  • shared_ptr allows multiple owners and keeps a reference count.
  • weak_ptr is used to break circular references and does not affect reference count.

Next Topic

Next, learn about Lambda Expressions in C++.