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;
}