一、简介由于 C++ 语言没有自动内存回收机制,程序员每次 new 出来的内存都要手动 delete 。程序员忘记 delete ,流程太复杂,最终导致没有 delete ,异常导致程序过早退出,没有执行 delete 的情况并不罕见。用智能指针便可以有效缓解这类问题,本文主要讲解参见的智能指针的用法。包括: std::auto_ptr 、boost::scoped_ptr 、boost::shared_ptr 、 boost::scoped_array 、boost::shared_array 、boost::weak_ptr 、boost:: intrusive_ptr 。你可能会想,如此多的智能指针就为了解决 new 、delete 匹配问题,真的有必要吗?看完这篇文章后,我想你心里自然会有答案。下面就按照顺序讲解如上 7种智能指针( smart_ptr )。二、具体使用 1、总括对于编译器来说,智能指针实际上是一个栈对象,并非指针类型,在栈对象生命期即将结束时,智能指针通过析构函数释放有它管理的堆内存。所有智能指针都重载了“operator-> ”操作符,直接返回对象的引用,用以操作对象。访问智能指针原来的方法则使用“.”操作符。访问智能指针包含的裸指针则可以用 get() 函数。由于智能指针是一个对象, 所以 if(my_smart_object) 永远为真,要判断智能指针的裸指针是否为空,需要这样判断: if(()) 。智能指针包含了 reset() 方法,如果不传递参数(或者传递 NULL ),则智能指针会释放当前管理的内存。如果传递一个对象,则智能指针会释放当前对象,来管理新传入的对象。我们编写一个测试类来辅助分析: class Simple {public: Simple(int param =0){number =param; std::cout <<"Simple: "<<number <<std::endl; }~Simple() {std::cout <<"~Simple: "<<number <<std::endl; }void PrintSomething() {std::cout <<"PrintSomething: "<<() << std::endl; }std::string info_extend; int number; };2、std::auto_ptr std::auto_ptr 属于 STL ,当然在 namespace std 中,包含头文件#include<memory> 便可以使用。 std::auto_ptr 能够方便的管理单个堆内存对象。我们从代码开始分析: void TestAutoPtr() {std::auto_ptr<Simple> my_memory(new Simple(1)); //创建对象,输出: Simple :1if(()) {//判断智能指针是否为空 my_memory->PrintSomething(); // 使用 operator-> 调用智能指针对象中的函数 ()->info_extend ="Addition"; //使用 get() 返回裸指针,然后给内部对象赋值 my_memory->PrintSomething(); // 再次打印,表明上述赋值成功(*my_memory).info_extend +="other"; //使用 operator* 返回智能指针内部对象,然后用“.”调用智能指针对象中的函数 my_memory->PrintSomething(); // 再次打印,表明上述赋值成功}}//my_memory 栈对象即将结束生命期,析构堆对象 Simple(1) 执行结果为: Simple: 1PrintSomething: PrintSomething: Addition PrintSomething: Addition other ~Simple: 1上述为正常使用 std::auto_ptr 的代码,一切似乎都良好,无论如何不用我们显示使用该死的 delete 了。其实好景不长,我们看看如下的另一个例子: void TestAutoPtr2() {std::auto_ptr<Simple> my_memory(new Simple(1)); if(()) { std::auto_ptr<Simple> my_memory2; //创建一个新的 my_memory2 对象 my_memory2 =my_memory; //复制旧的 my_memory 给my_memo
智能指针 来自淘豆网www.taodocs.com转载请标明出处.