由于最近研究的一个项目是用C++开发的, 所以不得不重温一下C++, 自己刚开始工作时候用的就是C++, 好熟悉的感觉.
智能指针——scoped_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 ...
did something
destroying implementation
Test End.
本文介绍并展示了C++中智能指针scoped_ptr的基本用法,通过一个简单示例说明了如何利用scoped_ptr自动管理堆上分配的对象,确保资源在不再需要时能被正确释放。
4998

被折叠的 条评论
为什么被折叠?



