您的位置:首页 > 运维架构

boost之scoped_ptr

2008-12-11 09:34 302 查看
c++标准库提供了std::auto_ptr

和boost::scoped_ptr的功能基本类似,
但有一点不一样,就是scoped_ptr不能移交指针所有权,
而std::auto_ptr可以移交指针。

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

using boost::scoped_ptr;
using std::cout;
using std::endl;
using std::auto_ptr;

class A {
public:
A() {
cout << "A:A()" << endl;
}
A(const A&) {
cout << "A:A(const A&)" << endl;
}
void fun() {
cout << "A:fun()" << endl;
}
~A() {
cout << "A:~A()" << endl;
}
};

int main()
{
auto_ptr<A> auto_pA(new A);
auto_pA->fun();
auto_ptr<A> auto_pA2(auto_pA);
cout << auto_pA.get() << endl; //0, auto_pA已经释放原指针(vc6.0有未释放的bug)
auto_pA2->fun();
scoped_ptr<A> scoped_pA(new A);
scoped_pA->fun();
//error, scoped_ptr不允许被复制
//scoped_ptr<A> scoped_pA2(scoped_pA);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: