zoukankan      html  css  js  c++  java
  • Effective C++ Item 14 Think carefully about copying behavior in resource-managing classe

    In C++, the only code that guaranteed to be executed after an exception is thrown are the destructors of objects residing in stack and that's why we need RAII. We don't always deal with head based objects, so instead with using auto_ptrs and shared_ptrs, sometimes we need to create our own resource managment class. And here are some rules you should follow:

    For coping constructor and coping assignment operator

    1. prohibit copying. If copying an RAII object makes no sense, you should explicitly prohibit it. You can either declare copy constructor private or inherit from Uncopyable class (see Item 6)

    2. Reference-count the underlying resources. Sometimes it's desirable to hold on the resource until the last object using it is destroyed. When that's the case, copying an RAII object should increse the count of the number of referring to that object. That is how shared_ptr implement copying behavior. So RAII can implement reference-counting copying by containing a shared_ptr data member. In addition, if you don't want to delete the resource when the reference count goes to 0 which is the default behavior of shared_ptr, you can provide a customized "deleter" to shared_ptr which will be called when reference count goes to 0.

    class Lock{
    public:
    	explicit Lock(Mutex *pm)
    	: mutexPtr(pm, unlock) {
    		lock(mutexPtr.get());
    	}
    	
    private:
    	std::tr1::shared_ptr<Mutex> mutexPtr;
    };
    

      

    3. copy the underlying resources

    In this case, the only reason to use recource-managing class is to make sure that resource would be released after you done with it. You need to make a deep copy of underlying resource

    4. Transfer the ownership of underlying resources

    Sometimes, you want to keep only one RAII object refers to raw resource, you need to transfer the ownership to new instance while copying. This kind of behavior is implemented by auto_ptr

  • 相关阅读:
    sqlite数据库如何远程连接?
    redis的两种持久化方案
    Netty入门系列(1) --使用Netty搭建服务端和客户端
    使用MQ消息队列的优缺点
    Netty基础系列(3) --彻底理解NIO
    Netty基础系列(2) --彻底理解阻塞非阻塞与同步异步的区别
    Netty基础系列(1) --linux网路I/O模型
    Jedis异常解决:NOAUTH Authentication required
    java并发编程(2) --Synchronized与Volatile区别
    java并发编程(1) --并发基础及其锁的原理
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3573337.html
Copyright © 2011-2022 走看看