Smart Pointers

Smart Pointers (unique_ptr, shared_ptr) in C++

IntermediateTopic: Memory Management Programs
Back

C++ Smart Pointers Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <memory>
using namespace std;

class MyClass {
private:
    int value;

public:
    MyClass(int v) : value(v) {
        cout << "MyClass object created with value: " << value << endl;
    }
    
    void display() {
        cout << "Value: " << value << endl;
    }
    
    ~MyClass() {
        cout << "MyClass object destroyed (value: " << value << ")" << endl;
    }
};

int main() {
    cout << "=== unique_ptr ===" << endl;
    {
        // unique_ptr - exclusive ownership
        unique_ptr<MyClass> ptr1 = make_unique<MyClass>(10);
        ptr1->display();
        
        // Cannot copy, but can move
        unique_ptr<MyClass> ptr2 = move(ptr1);
        if (ptr1 == nullptr) {
            cout << "ptr1 is now null (ownership transferred)" << endl;
        }
        ptr2->display();
    }  // Automatically deleted
    
    cout << "\n=== shared_ptr ===" << endl;
    {
        // shared_ptr - shared ownership
        shared_ptr<MyClass> ptr1 = make_shared<MyClass>(20);
        cout << "Reference count: " << ptr1.use_count() << endl;
        
        {
            shared_ptr<MyClass> ptr2 = ptr1;  // Share ownership
            cout << "Reference count: " << ptr1.use_count() << endl;
            ptr2->display();
        }  // ptr2 goes out of scope
        
        cout << "Reference count: " << ptr1.use_count() << endl;
        ptr1->display();
    }  // Automatically deleted when count reaches 0
    
    cout << "\nAll objects automatically destroyed" << endl;
    
    return 0;
}
Output
=== unique_ptr ===
MyClass object created with value: 10
Value: 10
ptr1 is now null (ownership transferred)
Value: 10
MyClass object destroyed (value: 10)

=== shared_ptr ===
MyClass object created with value: 20
Reference count: 1
Reference count: 2
Value: 20
Reference count: 1
Value: 20
MyClass object destroyed (value: 20)

All objects automatically destroyed

Understanding Smart Pointers

Smart pointers automatically manage memory, preventing memory leaks. unique_ptr provides exclusive ownership - only one pointer can own the object. shared_ptr allows multiple pointers to share ownership with reference counting. When the last shared_ptr is destroyed, the object is automatically deleted. Smart pointers are part of C++11 and are preferred over raw pointers for automatic memory management.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents