Concept

std::shared_ptr is a smart pointer that enables shared ownership of a dynamically allocated object. Multiple shared_ptr instances can point to the same resource, and the resource is deallocated only when the last owner goes out of scope or is reset. Internally, shared_ptr maintains a reference count to track the number of active owners.

Key Characteristics

Basic Usage

#include <iostream>
#include <memory>

class Resource {
public:
    Resource(int id) : id_(id) { std::cout << "Resource " << id_ << " acquired.\\n"; }
    ~Resource() { std::cout << "Resource " << id_ << " released.\\n"; }
    void show() const { std::cout << "Resource ID: " << id_ << "\\n"; }
private:
    int id_;
};

int main() {
    std::shared_ptr<Resource> sp1 = std::make_shared<Resource>(10);
    std::shared_ptr<Resource> sp2 = sp1;  // Shared ownership
    std::cout << "Use count: " << sp1.use_count() << "\\n"; // Outputs 2
    sp2->show();

    sp2.reset(); // Decreases use count
    std::cout << "Use count after reset: " << sp1.use_count() << "\\n"; // Outputs 1

    return 0;
}
// Resource released when last shared_ptr goes out of scope

Important Functions

Use Cases

  1. Shared Ownership in APIs: Multiple clients accessing the same object.
  2. Graph or Tree Structures: Nodes may be referenced by multiple parents.
  3. Callbacks and Observers: Objects registered to an event system can outlive the owner.
  4. Multithreaded Workflows: Safely distribute shared resources across threads (synchronization still needed for object access).

Memory Considerations

shared_ptr uses a control block that holds: