其实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的时候一定要多加小心。