学boost的第二课,写了一点关于boost::smart_ptr的实验。因为本身是学物理的,所以对做实验比较感兴趣。 理论的实践总是有一道鸿沟的,所以,这里写的东西,只是为了试一试smart_ptr罢了,对于实际的运用,还差得远!
Boost为我们提供了auto_ptr之外的另一个选择,网上有很多比较auto_ptr boost::smart_ptr loki的文章,我个人觉得,这些库都是大牛们写的,又有足够的强度,本不用比来比去的,如果有差别,也只不过是在不同的环境下有不同的表现罢了。只要用对了地方,没有什么可比的。“武术本身并没有高低之分,只有习武之人才有强弱之别。”如果你觉得不好用,可能是自己修炼不够吧。
本实验用了对照法,把不用smart_ptr的,造成泄漏的程序,和用了smart_ptr,安全释放的程序对比写出。在实际中,你是不可能见到这样的情况的,这里都是对实际情况的最简单化,理想版!闲话少说,看程序:
#include <iostream>
#include <memory>
#include <boost/smart_ptr.hpp>
//没有用smart_ptr的函数
void no_smart_ptr(void) //1亿次,近乎溃
{
int* i=new int(100);
}
//标准库的智能pointer
void use_auto_ptr(void) //1亿次,运行时间很长,但内存没有涨,不到2M,基本在1.7M
{
std::auto_ptr<int> i(new int(1));
}
//不可复制的pointer
void use_scoped_ptr(void) //1亿次,运行时间很长,但内存没有涨,不到2M,基本在1.7M
{
boost::scoped_ptr< int > i(new int(10));
// boost::scoped_ptr< int > j(i); //这是不允许的!
}
//可以共享的pointer
void use_shared_ptr(void) //没有试用长时间,内存没有涨,成功release
{
boost::shared_ptr<int> i(new int(1)); //use_count=1
boost::shared_ptr<int> j(i); //use_count=2
}
//没有用smart_ptr的数组程序
void no_smart_array(void) //1W次,6M空间
{
int* i=new int[100];
}
//标准库没有提供对array的auto_ptr,可能是因为有vector吧。
//用于array的不可复制的smart_ptr
void use_scoped_array(void) //1W次,1.7M
{
boost::scoped_array<int> i(new int[100]);
//boost::scoped_array<int>j(i); //这是不允许的
}
//用于array的可复制的smart_ptr
void use_shared_array(void) //1W次,1.7M
{
boost::shared_array<int> i(new int[100]); //use_count=1
boost::shared_array<int> j(i); //use_count=2
}
int main(int argc, char *argv[])
{
for (int i = 0; i < 100 ; i++)
{
for (int j = 0; j <100 ; j++)
{
//no_smart_ptr();
//use_auto_ptr();
//use_shared_ptr();
//no_smart_array();
//use_scoped_array();
//use_shared_array();
}
}
//等待结束
char c;
while(std::cin>>c);
return 0;
}