scoped_ptr

scoped_ptr是一个很类似auto_ptr的智能指针,它包装了new操作符在堆上分配的动态对象,能够保证动态创建的对象在任何时候都可以被正确的删除,但很重要的一点是scoped_ptr获取了对象的管理权,就无法再从它那里取回来

它只在对象析构的时候释放一次,对象析构的时候自动释放内存

source code
template<class T>
class scoped_ptr{
private:
    T *px;
    //private意味着指针不能被转让所有权
    scoped_ptr(scoped_ptr const &);
    scoped_ptr & operator=(scoped_ptr const &);
public:
    explicit scoped_ptr(T * p =0);
    ~scoped_ptr();
    //删除原指针,再保存新指针,如果p是空指针,scoped_ptr将不持有任何指针
    void reset(T* p=0);
    T & operator*()const;
    T * operator->()const;
    //返回scoped_ptr内部保存的原始指针,但不能对原始指针进行delete操作
    T * get()const;

    operator unspecified-bool-type() const;
    void swap(scoped_ptr & b);
};



用法:不允许拷贝和赋值
#include<boost/smart_ptr.hpp>
#include<iostream>
using namespace boost;
using namespace std;

class A
{
public:
    A(){
        cout << "A()" << endl;
    }
    ~A(){
        cout << "~A()" << endl;
    }
};

int main()
{
    scoped_ptr<int> p1(new int);
    *p1 = 100;
    cout << *p1 << endl;
    scoped_ptr<int> p2(new int);
    *p2 = 200;
    cout << *p2 << endl;
    //p1 = p2;不能转让所有权
    p1.reset();//now p is null
    if(p1)
        cout << *p1 << endl;//this code will not be execute
    scoped_ptr<A> p3(new A);
}


100
200
A()
~A()


auto_ptr是可以转让的
#include<boost/smart_ptr.hpp>
#include<iostream>
#include<cassert>
using namespace boost;
using namespace std;

int main()
{
    auto_ptr<int> ap(new int(10));
    cout << *ap << endl;
    scoped_ptr<int> sp(ap);//now ap is null
    assert(ap.get()==0);
    ap.reset(new int(101));
    cout << *ap << "," << *ap.get() << endl;
}

10
101,101

你可能感兴趣的:(C++,c,C#)