// shared_ptr is built-in RAII. // // A shared_ptr is a “counting pointer”. It keeps track of how many // shared owners this object has, via a counter. // // A new owner (via assignment) increments the counter. // When any owner is destroyed, the counter decrements. // // When the counter goes to zero, there are no more owners, // so the object itself is destroyed. // // You can assign a shared_ptr. It just increments the use count. #include #include using namespace std; // A class that tells you when instances are created or destroyed: class Loud { public: Loud() { clog << "Loud::Loud()\n"; } ~Loud() { clog << "Loud::~Loud()\n"; } }; int main() { shared_ptr p(new Loud); cout << p.use_count() << '\n'; { cout << p.use_count() << '\n'; auto q=p; cout << p.use_count() << '\n'; } cout << p.use_count() << '\n'; return 0; }