// unique_ptr is built-in RAII. // // A unique_ptr “owns” the pointed-to object. // When the unique_ptr is destroyed (usually, by falling out of scope) // then the pointed-to objected is destroyed, as well. // // You cannot assign a unique_ptr, because, then, there wouldn’t // be a unique owner. // // BTW, auto_ptr is deprecated. #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"; } void say() { clog << "Loud::say()\n"; } }; void foo() { unique_ptr p(new Loud); p->say(); } int main() { unique_ptr a(new Loud[3]); // Note the [] a[2].say(); // When this function exits (via normal exit or throw), // then p gets destroyed, and its dtor deallocates the Loud. cout << "Calling foo()\n"; foo(); cout << "Back from foo()\n"; return 0; }