Sobes.tech
Middle

What smart pointers do you know in C++?

sobes.tech AI

Answer from AI

  • std::unique_ptr - a unique owner of an object, cannot be copied but can be moved.
    #include <memory>
    
    int main() {
        std::unique_ptr<int> ptr(new int(10)); // Creation
        // std::unique_ptr<int> ptr2 = ptr; // Compilation error - no copying
        std::unique_ptr<int> ptr3 = std::move(ptr); // Move ownership
        return 0;
    }
    
  • std::shared_ptr - a shared owner, counts references to the object. The object is deleted when the reference count reaches zero.
    #include <memory>
    #include <iostream>
    
    int main() {
        std::shared_ptr<int> ptr(new int(20));
        std::cout << "Refs: " << ptr.use_count() << std::endl; // 1
    
        std::shared_ptr<int> ptr2 = ptr; // Copying owner
        std::cout << "Refs: " << ptr.use_count() << std::endl; // 2
    
        ptr.reset(); // Decrease reference count
        std::cout << "Refs: " << ptr2.use_count() << std::endl; // 1
    
        return 0;
    }
    
  • std::weak_ptr - a non-owning observer, used to prevent cyclic references between shared_ptr. Does not increase the reference count. To access the object, convert it to shared_ptr using the lock() method.
    #include <memory>
    #include <iostream>
    
    int main() {
        std::shared_ptr<int> shared_ptr(new int(30));
        std::weak_ptr<int> weak_ptr = shared_ptr; // Create weak_ptr
    
        if (auto locked_ptr = weak_ptr.lock()) {
            std::cout << "Value: " << *locked_ptr << std::endl; // Access to object
        } else {
            std::cout << "Object expired." << std::endl;
        }
    
        shared_ptr.reset(); // Object deleted
    
        if (auto locked_ptr = weak_ptr.lock()) {
            std::cout << "Value: " << *locked_ptr << std::endl;
        } else {
            std::cout << "Object expired." << std::endl; // Object deleted
        }
    
        return 0;
    }
    
  • std::auto_ptr - deprecated (removed in C++17), a smart pointer with move semantics on copy, which could lead to errors. Use std::unique_ptr instead.
Pointer Ownership semantics Copying Moving Cyclic references
unique_ptr Unique No Yes Not applicable
shared_ptr Shared Yes Yes Can cause
weak_ptr Does not own Yes Yes Prevents
auto_ptr Moving (deprecated) No (except) Implicit Not applicable