boost - 智能指针之scoped_ptr
scoped_ptr不具备“value”语义,不可以进行拷贝和赋值,因此不涉及所有权(ownership)的转化,因此比起std::auto_ptr和boost:shared_ptr更加安全。
其只是遵循RAII(Resource Acquisition Is Initialisation)原则,对象初始化时即获取资源,对象析构时释放资源。
使用scoped_ptr可以简化代码,保证异常安全.
scoped_ptr实现简单,与原始指针效率相当.
注意:scoped_ptr不可以用在STL标准容器中;scoped_ptr不可以保存动态分配的数组指针
Example
#include <boost/scoped_ptr.hpp>
#include <iostream>
struct Shoe { ~Shoe() { std::cout << “discard my shoe\n”; } };
class MyClass {
boost::scoped_ptr<int> ptr;
public:
MyClass() : ptr(new int) { *ptr = 0; }
int add_one() { return ++*ptr; }
};
int main()
{
boost::scoped_ptr<Shoe> x(new Shoe);
[...]