Attention:
- The assignment Raii object must replicate the resources it manages, so the copy behavior of the resource determines the copy behavior of the Raii object.
- General and common RAII copy behavior is: Suppress the copy, the implementation of reference counting method.
void lock (Mutex* PM); void unlock (mutex* class lock{ public : explicit Lock (Mutex* lock (MUTEXPTR); } ~lock () {unlock (mutexptr);} private : Mutex * mutexptr;}; Mutex m;.. {Lock ml ( &m); ...} // at the end of the block, automatically unlock the lock
Lock ML1 (&m);
Lock ML2 (ML1); What happens when you copy Ml1 to ML2?
Solutions
1. Disable copying and define the copy operation as private.
2. Use the reference notation. Here you can use the compiler-generated default destructor, which automatically calls destructors for non-static member variables (in this case, mutexptr). Mutexptr's destructor automatically calls the Tr1::shared_ptr's delete (in this case, unlock) when the reference count is 0.
class Lock {public: Explicit Lock (mutex* pm) : mutexptr (PM, unlock) { Lock (Mutexptr. Get ();) } Private : std::tr1::shared_ptr<Mutex> mutexptr;}
Effective C + + clause 14: Careful copying of behavior in resource management classes