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.
#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
shared_ptr uses a control block that holds: