scoped_ptr vs auto_ptr

其实scoped_ptr和auto_ptr的用法几乎都是一样的。只不过scoped_ptr在auto_ptr的基础上,采取了一些措施,将auto_ptr运行时的错误,让scoped_ptr在编译器就能够被发现。

下面是auto_ptr的代码,在运行期间会产生一个错误:
#include <iostream>

using namespace std;

class Person
{
public:
    Person() : age(23), name("zyc")
    {
        cout << "create person" << endl;
    }

    virtual ~Person()
    {
        cout << "delete person" << endl;
    }

    void print()
    {
        cout << "age : " << this->age << "   name: " << this->name << endl;
    }
private:
    int age;
    string name;
};

int main()
{
    Person *p = new Person();
    auto_ptr<Person> bp;
    auto_ptr<Person> ap(p);

    bp = ap;
    // 因为控制权已经交给bp,所以在运行期间,在这里会产生一个错误。
    ap->print();
    bp->print();

    return 0;
}

如下为scoped_ptr的代码:

#include <iostream>
#include <boost/smart_ptr.hpp>

using namespace std;
using namespace boost;

class Person
{
public:
    Person() : age(23), name("zyc")
    {
        cout << "create person" << endl;
    }

    virtual ~Person()
    {
        cout << "delete person" << endl;
    }

     void print()
    {
        cout << "age : " << this->age << "   name: " << this->name << endl;
    }
private:
    int age;
    string name;
};

int main()
{
    Person *p = new Person();
    scoped_ptr<Person> sp1(p);
 // 这里在编译的时候会产生一个错误,禁止将控制权交给sp2,因为scoped_ptr禁止拷贝构造和赋值构造,来防止auto_ptr中会发生的错误
 //    scoped_ptr<Person> sp2(sp1);

    sp1->print();
//    sp2->print();

    return 0;
}

所以在使用C++标准库提供的智能指针auto_ptr的时候一定要多加小心。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值