工作中需要写一个cpp,但是因为我的水平太差,leader为了避免我写的程序内存泄漏要求我使用boost shared_ptr
以下是构建一个demo的过程
/home/a.cpp:
#include <iostream>
#include <boost/shared_ptr.hpp>
class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};
void test()
{
boost::shared_ptr<implementation> sp1(new implementation());
std::cout<<"The Sample now has "<<sp1.use_count()<<" references\n";
boost::shared_ptr<implementation> sp2 = sp1;
std::cout<<"The Sample now has "<<sp2.use_count()<<" references\n";
sp1.reset();
std::cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references\n";
sp2.reset();
std::cout<<"After Reset sp2.\n";
}
int main()
{
test();
return 0;
}
编译:
g++ -I /home/boost_1_43_0/include/ a.cpp
运行和结果:
LINUX:/home # ./a.out
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
destroying implementation
After Reset sp2.

本文演示了如何通过使用Boost库中的shared_ptr智能指针来避免C++编程中的内存泄漏问题,通过实例代码详细展示了shared_ptr的引用计数机制及reset方法的使用。
6230

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



