How do I use unique_ptr/shared_ptr in C++11?

In C++11, smart pointers like std::unique_ptr and std::shared_ptr are used to manage the lifetime of dynamically allocated objects, ensuring proper memory management and reducing the possibility of memory leaks.

Using unique_ptr

std::unique_ptr is used when you want to have sole ownership of an object, ensuring that no two unique pointers point to the same object.


#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass() { std::cout << "MyClass created" << std::endl; }
    ~MyClass() { std::cout << "MyClass destroyed" << std::endl; }
};

int main() {
    std::unique_ptr ptr1(new MyClass());
    // std::unique_ptr ptr2 = ptr1; // This will cause a compile error
    std::unique_ptr ptr2 = std::move(ptr1); // Transfer ownership
    return 0;
}
    

Using shared_ptr

std::shared_ptr is used when you want to allow multiple owners for the same object. It keeps track of how many shared pointers point to the same object.


#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass() { std::cout << "MyClass created" << std::endl; }
    ~MyClass() { std::cout << "MyClass destroyed" << std::endl; }
};

int main() {
    std::shared_ptr ptr1(new MyClass());
    {
        std::shared_ptr ptr2 = ptr1; // Shared ownership
        std::cout << "Use count: " << ptr1.use_count() << std::endl; // 2
    }
    std::cout << "Use count after ptr2 goes out of scope: " << ptr1.use_count() << std::endl; // 1
    return 0;
}
    

unique_ptr shared_ptr C++11 smart pointers memory management memory leaks ownership management