Item 13 管理在堆上new出来的对象
2011-04-25 13:26
127 查看
void f() { std::auto_ptr<Investment> pInv(createInvestment()); ... }
创建Investment资源之后立即交给资源管理器auto_ptr
,这叫Resource Acquisition Is Initialization (RAII)。
资源管理器在dtor里销毁资源。如果发生异常,会很麻烦。
不要用多个auto_ptr管理同一个资源。否则会发生多次销毁。auto_ptr本身也改装了copy动作(copy ctor和assignment operator)。
std::auto_ptr<Investment> pInv1(createInvestment()); std::auto_ptr<Investment> pInv2(pInv1); // pInv2 now points to the object; pInv1 is now null pInv1 = pInv2; // now pInv1 points to the object, and pInv2 is null
因为有着这种奇怪的拷贝行为,所以auto_ptr不能用于管理STL容器内的元素。STL容器要求,其元素必须能正常拷贝。
可使用“引用计数智能指针”:reference-counting smart pointer (RCSP)来代替auto_ptr。和垃圾收集类似,不同之外在于RCSP不能处理“循环引用”。
shared_ptr就是一种RCSP:
void f() { ... std::tr1::shared_ptr<Investment> pInv(createInvestment()); ... }
对于初始化,和auto_ptr没什么不同。
void f() { ... std::tr1::shared_ptr<Investment> pInv1(createInvestment()); std::tr1::shared_ptr<Investment> pInv2(pInv1); // both pInv1 and pInv2 now point to the object pInv1 = pInv2; // ditto — nothing has changed ... } // pInv1 and pInv2 are destroyed, and the object they point to is automatically deleted
auto_ptr和tr1::shared_ptr都用delete来析构对象,而非delete[]。所以不能管理对象数组。但是如果误用,编译器不报错。
boost::scoped_array和boost::shared_array可管理数组对象。
相关文章推荐
- Effective C++ Item 13 以对象管理资源
- 读书笔记 effective c++ Item 13 用对象来管理资源
- <Effective C++> (Item 13-15): 以对象管理资源
- 读书笔记 effective c++ Item 13 用对象来管理资源
- effective c++ item13:使用对象管理资源
- effective c++ Item 17: 在一个独立的语句中将 new 出来的对象存入智能指针
- [翻译] Effective C++, 3rd Edition, Item 17: 在 standalone statements(独立语句)中将 new 出来的 objects(对象)存入 smart pointers(智能指针)
- 读书笔记 effective c++ Item 17 使用单独语句将new出来的对象放入智能指针
- Item 17 将new出来的对象存入智能指针
- Item 13:使用对象(智能指针)来管理资源 Effective C++笔记
- Effective C++ Item 13-以对象管理资源
- 条款13:以对象管理资源
- 条款13:以对象管理资源(use objects to manage resources)
- 条款13:以对象管理资源
- effective c++ 条款13 以对象管理资源
- Effective C++ 13 以对象管理资源 笔记
- Item3:Use objects to manage resources--以对象管理资源
- Effective C++ 条款13学习笔记:以对象管理资源
- TDD Tip:方法内部New出来的对象如何Mock
- Effective C++ 条款13:以对象管理资源