Item 14:think carefully about copying behavior in resource-managing classes.
In Item 13: Using objects to manage resources, RAII-based resource management objects are presented, auto_ptr and shared_ptr . Smart pointers can have different copy policies. When you implement such a resource management object, you need to pay special attention. For example, a typical RAII-style mutex implementation:
class Lock { Public: Explicit Lock(Mutex *pm):mutexptr(pm){ Lock(mutexptr); } ~Lock(){ Unlock(mutexptr); }Private: Mutex *mutexptr;};
explicit qualifies the constructor to prevent the implicit conversion from occurring: lock l = pm .
The mutex is very simple to use, just to create a C + + code block for each critical section, where Lock the local variables are defined:
Mutex m; //define Mutual exclusion lock{ //Create a code block to define a critical section Lock M1(&m); //Mutex lock plus lock ... //Critical area operation} //M1 is destroyed when exiting scope, automatic unlocking of mutex
when m1 is copied? Add the code of the current scope to the same critical section? Copy the mutex and define a new critical section? Or simply swapping the mutex for a resource manager? The copy behavior of the resource management object depends on the copy behavior of the resource itself, and the resource management object can also decide its own copy behavior according to the business need. . The optional copy behavior is the following four kinds:
- Copying is prohibited. Simply private inheritance of a
Uncopyable class allows it to disallow copying. See also: Item 6: Disable the default methods that are not required.
Reference count, usingshared_ptrThe logic. Justshared_ptrThe constructor provides a second argumentdeleterCalled when the reference count is 0 o'clock. SoLockYou can do this by aggregating ashared_ptrMember to implement the reference count:
class Lock{ Public: Explicit Lock(Mutex *pm): mutexptr(pm, Unlock){ Lock(mutexptr.Get()); } Private: STD::shared_ptr<Mutex> mutexptr; } //' Lock ' destructor causes ' mutexptr ' to be destroyed, and ' mutexptr ' count to 0 o'clock ' unlock (Mutexptr.get ()) ' will be called. };
Copy the underlying resource. When you can have any underlying resource, you can copy it directly. For example string : Memory has a pointer to space, and when it is copied it copies that space.
Transfer ownership of the underlying resource. auto_ptrThis is done by handing over resources to another resource management object, with its own resources empty.
Unless noted, this blog article is original, reproduced please link to the form of this article address: http://harttle.com/2015/08/04/effective-cpp-14.html
Copyright NOTICE: This article is for bloggers original articles, reproduced please attach the original link.
Item 14: Resource Management classes pay special attention to copy behavior effective C + + notes