示例代码如下:
#include <iostream>
#include <boost/smart_ptr.hpp>
class P
{
public:
P()
{
t = 7;
}
~P()
{
t = 10;
}
private:
int t;
};
class posix_file
{
public:
posix_file(char* filename)
{
std::cout << "open file"<< filename << std::endl;
}
~posix_file()
{
std::cout << "close file." << std::endl;
}
};
int main()
{
std::auto_ptr<P> p1(new P);
std::auto_ptr<P> p2;// = new P();
p2.reset(new P());
//boost::scoped_ptr类摘要
/*
template <class T>
class scoped_ptr
{
private:
T* px;
//由于拷贝构造函数和赋值运算符(甚至是全局的!=、==运算符)申明为私有,
//故该类不能使用这些方法
scoped_ptr(scoped_ptr const &);
scoped_ptr& operator=(scoped_ptr const &);
public:
scoped_ptr(T* p = 0);
~scoped_ptr();
void reset(T* p = 0);
T& operator*() const;
T& operator->() const;
T* get() const;
operator unspecified-bool-type() const;
void swap(scoped_ptr& b);
};
*/
boost::scoped_ptr<std::string> p3(new std::string("helloworld!"));
//可以像普通指针一样解引用
std::cout << *p3 << std::endl;
std::cout << p3->size() << std::endl;
//以下代码非法:不允许对p3进行指针算术操作
// p3++;
//不允许对p4进行拷贝构造
//boost::scoped_ptr<std::string> p4 = p3;
//可以对p3进行bool语境测试
if (p3)
{
//do something
}
//reset方法仅仅是为了演示,不推荐这么用。
p3.reset();
assert(p3 == NULL);
//文件类在离开作用域之后会自动释放文件资源
boost::scoped_ptr<posix_file> pfile(new posix_file("test.txt"));
return 0;
}
boost::scoped_ptr与std::auto_ptr的区别是:前者的设计意图是指针语义不可以转移的,根本原因是其拷贝构造函数和赋值运算符被设置为私有;而后者的指针语义是可以转移的(注意:在传递过程中要特别小心,以免出错)。示例如下:
#include <iostream>
#include <boost/smart_ptr.hpp>
int main()
{
std::auto_ptr<int> ap(new int(10));
boost::scoped_ptr<int> sp(ap);
assert(ap.get() == 0); //ap不再拥有指针
ap.reset(new int(20));
std::cout << *sp << ", " << *ap << std::endl;
std::auto_ptr<int> ap2;
ap2 = ap; //ap2从ap处获得指针所有权
assert(ap.get() == 0); //ap不再拥有指针
boost::scoped_ptr<int> sp2;
//赋值操作无法编译通过
sp2 = sp;
return 0;
}
std::auto_ptr和boost::scoped_ptr对象均不能作为容器的元素,因为不满足stl对元素的要求,具体细节见:
http://www.cppblog.com/happem/archive/2012/08/27/188415.html