What Are the Main Differences Between the Different C++ Smart Pointers (`unique_ptr`, `shared_ptr`, `weak_ptr`)?

C++ offers three main smart pointers: `unique_ptr`, `shared_ptr`, and `weak_ptr`. `unique_ptr` provides exclusive ownership and cannot be copied. `shared_ptr` allows multiple owners with reference counting. `weak_ptr` is used to break circular references and does not affect the reference count.

Examples:

#include 

void uniquePointerExample() {
    std::unique_ptr ptr1(new int(10));
    // std::unique_ptr ptr2 = ptr1; // Error: cannot copy unique_ptr
}

void sharedPointerExample() {
    std::shared_ptr ptr1(new int(20));
    std::shared_ptr ptr2 = ptr1; // Allowed: both own the resource
}

void weakPointerExample() {
    std::shared_ptr ptr1(new int(30));
    std::weak_ptr weakPtr = ptr1; // weak_ptr does not own the resource
}

Leave a Reply

Your email address will not be published. Required fields are marked *