Effective C + + clause 14: Careful copying of behavior in resource management classes

Source: Internet
Author: User
Tags mutex

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.