The idea of managing resources with objects is often referred to as "the opportunity for resource acquisition is the time of initialization" (RAII)
Auto_ptr is automatically deleted when it is destroyed, so be careful not to let multiple auto_ptr point to the same object at the same time, otherwise the object will be deleted more than once, the behavior is undefined
Auto_ptr has a property: If you copy them by copying constructors or copy construction operators, they become null, and the copied pointers get the unique ownership of the resources
classinvestment{Private: Doublevalue; Public: Investment (Doubleval): Value (val) {}DoubleGetValue () {returnvalue; }};investment* Createinvestment (Doubleval) { return NewInvestment (val);}intMain () {auto_ptr<Investment> PInv1 (Createinvestment (3.0)); cout<< Pinv1->getvalue () <<Endl; Auto_ptr<Investment>pInv2 (PINV1); cout<< pinv1->getvalue () << Endl;//error, PINV1 is null}
Can use shared_ptr to replace the AUTO_PTR,SHARED_PTR has a disadvantage: cannot break the ring reference, if the two objects that have not been used to refer to each other, it seems to be in the state of being used
Auto_ptr and shared_ptr both do delete instead of delete[in their destructor, so using auto_ptr or shared_ptr on a dynamically allocated array is a bad idea.
Summarize:
1. To prevent resource leaks, use the Raii object, which obtains resources in the constructor and releases resources in the destructor
2. Two commonly used RAII classes are shared_ptr and Auto_ptr, the former being a better choice (both for managing resources on the heap)
classlock{ Public: ExplicitLock (mutex*pm): mutexptr (PM) {mutexptr-Lock(); } ~Lock () {mutexptr-unlock (); }Private: Mutex*mutexptr;};----------------------------------------------------------------------------//using reference counting for underlying resourcesclasslock{ Public: ExplicitLock (mutex* pm): mutexptr (pm,pm->unlock) {mutexptr.Get()Lock(); }Private: Tr1::shared_ptr<mutex>mutexptr;};
SHARED_PTR allows you to specify a delete (deleter), which is a function or function object that is called when the number of references is 0 o'clock (this function does not exist in auto_ptr, it always deletes the pointer)
"Effective C + +" resource management