boost::scoped_ptr和std::auto_ptr非常类似,是一个简单的智能指针,它能够保证在离开作用域后对象被自动释放。下列代码演示了该指针的基本应用:
#include <string>
#include <iostream>
#include <boost/scoped_ptr.hpp>
class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};
void test()
{
boost::scoped_ptr<implementation> impl(new implementation());
impl->do_something();
}
void main()
{
std::cout<<"Test Begin ... \n";
test();
std::cout<<"Test End.\n";
}
该代码的输出结果是:
Test Begin ... |
可以看到:当implementation类离其开impl作用域的时候,会被自动删除,这样就会避免由于忘记手动调用delete而造成内存泄漏了。
boost::scoped_ptr特点: