Resource Management #
13.Use objects tomanage resources #
- 获得资源后立刻放进管理对象,RAII(Resource Acquisition Is Initialization资源获取时机便是初始化时机)
 - 管理对象运用析构函数确保资源被释放
 - auto_ptr和tr1::shared_ptr两者都在其析构函数内做delete而不是delete[]动作,vector和string几乎总是可以取代动态分配而得的数组,可以使用boost::scoped_array和boost::shared_array类
 
14.Think carefully about copying behavior in resource-managing classes #
- 
如果复制动作对RAII class 并不合理,考虑禁止复制
 - 
复制RAII对象必须一并复制它所管理的资源,常见的RAII class copying行为是:抑制copying,施行引用计数法
 
15.Provide access to raw resources in resource-managing classes #
- 
APIs往往要求访问原始资源,所以每个RAII class应该提供一个取得其所管理之资源的办法
 - 
通常通过调用abort结束程序,来阻止异常从析构函数传播出去
 
class Font{
public:
    explicit Font(FontHandle fh):f(fh)
    {}
    ~Font()
    {
        releaseFont(f);
    }
    operator FontHandle() const;//隐式转换函数
    {
        return f;
    }
private:
    FontHandle f;
}
16.Use the same form in corresponding uses of new and delete #
- 
new表达式中使用[],必须相应的delete表达式中了使用[]
 - 
不要对数组形式做typeddef动作
 
typedef std::string AddressLines[4];//不建议
std::string* pal = new AddressLines;
delete pal;//未定义的行为
17.Store newed objects in smart pointers in standalone statements #
在单独语句内以智能指针存储newd所得对象
int priority();
void processWidget(std::shared_ptr<Widget> pw,int priority);
//调用方式1,不推荐
processWidget(std::shared_ptr<Widget> pw(new Widget),priority());
//调用方式2
std::shared_ptr<Widget> pw(new Widget);//在单独语句内以智能指针存储newd所得对象
processWidget(pw,priority());