[关闭]
@coolwyj 2014-12-05T06:07:25.000000Z 字数 8272 阅读 2333

智能指针(2)

C++


参考:点击这里


简介

由于 C++ 语言没有自动内存回收机制,程序员每次new出来的内存都要手动delete。程序员忘记delete,流程太复杂,最终导致没有delete,异常导致程序过早退出,没有执行delete的情况并不罕见。

用智能指针便可以有效缓解这类问题,本文主要讲解参见的智能指针的用法。包括:std::auto_ptrboost::scoped_ptrboost::shared_ptrboost::scoped_arrayboost::shared_arrayboost::weak_ptrboost::intrusive_ptr


总括

对于编译器来说,智能指针实际上是一个栈对象,并非指针类型,在栈对象生命期即将结束时,智能指针通过析构函数释放有它管理的堆内存。所有智能指针都重载了operator->操作符,直接返回对象的引用,用以操作对象。访问智能指针原来的方法则使用.操作符。

访问智能指针包含的裸指针则可以用get()函数。
由于智能指针是一个对象,所以if(my_smart_object)永远为真,要判断智能指针的裸指针是否为空,需要这样判断:if(my_smart_object.get())

智能指针包含了reset()方法,如果不传递参数(或者传递NULL),则智能指针会释放当前管理的内存。如果传递一个对象,则智能指针会释放当前对象,来管理新传入的对象。

如下是一个辅助测试类:

  1. class Simple {
  2. public:
  3. Simple(int param = 0) {
  4. number = param;
  5. std::cout << "Simple: " << number << std::endl;
  6. }
  7. ~Simple() {
  8. std::cout << "~Simple: " << number << std::endl;
  9. }
  10. void PrintSomething() {
  11. std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;
  12. }
  13. std::string info_extend;
  14. int number;
  15. };

1、std::auto_ptr
std::auto_ptr属于STL,当然在namespace std中,包含头文件#include<memory>便可以使用。
std::auto_ptr能够方便的管理单个堆内存对象。

从代码开始分析:

  1. void TestAutoPtr() {
  2. std::auto_ptr<Simple> my_memory(new Simple(1));
  3. // 创建对象,输出:Simple:1
  4. if (my_memory.get()) {
  5. // 判断智能指针是否为空
  6. my_memory->PrintSomething();
  7. // 使用 operator-> 调用智能指针对象中的函数
  8. my_memory.get()->info_extend = "Addition";
  9. // 使用 get() 返回裸指针,然后给内部对象赋值
  10. my_memory->PrintSomething();
  11. // 再次打印,表明上述赋值成功
  12. (*my_memory).info_extend += " other";
  13. // 使用 operator*返回智能指针内部对象,然后用“.”调用智能指针对象中的函数
  14. my_memory->PrintSomething();
  15. // 再次打印,表明上述赋值成功
  16. }
  17. }
  18. // my_memory 栈对象即将结束生命期,析构堆对象 Simple(1)

执行结果为:
Simple: 1
PrintSomething:
PrintSomething: Addition
PrintSomething: Addition other
~Simple: 1

上述为正常使用std::auto_ptr的代码,一切似乎都良好.

再看如下一个例子:

  1. void TestAutoPtr2() {
  2. std::auto_ptr<Simple> my_memory(new Simple(1));
  3. if (my_memory.get()) {
  4. std::auto_ptr<Simple> my_memory2;
  5. // 创建一个新的 my_memory2 对象
  6. my_memory2 = my_memory;
  7. // 复制旧的 my_memory 给 my_memory2
  8. my_memory2->PrintSomething(); // 输出信息,复制成功
  9. my_memory->PrintSomething(); // 崩溃
  10. }
  11. }

最终如上代码导致崩溃,如上代码时绝对符合 C++编程思想的,居然崩溃了,跟进 std::auto_ptr的源码后,我们看到,罪魁祸首是my_memory2 = my_memory,这行代码,my_memory2完全夺取了my_memory的内存管理所有权,导致my_memory悬空,最后使用时导致崩溃。
所以,使用std::auto_ptr时,绝对不能使用operator=操作符。作为一个库,不允许用户使用,确没有明确拒绝,多少会觉得有点出乎预料。

再来一个例子:

  1. void TestAutoPtr3() {
  2. std::auto_ptr<Simple> my_memory(new Simple(1));
  3. if (my_memory.get()) {
  4. my_memory.release();
  5. }
  6. }

执行结果为:
Simple: 1
我们创建出来的对象没有被析构,没有输出~Simple:1,导致内存泄露。当我们不想让my_memory继续生存下去,我们调用release()函数释放内存,结果却导致内存泄露(在内存受限系统中,如果my_memory占用太多内存,我们会考虑在使用完成后,立刻归还,而不是等到my_memory结束生命期后才归还)。

正确的代码应该为:

  1. void TestAutoPtr3() {
  2. std::auto_ptr<Simple> my_memory(new Simple(1));
  3. if (my_memory.get()) {
  4. Simple* temp_memory = my_memory.release();
  5. delete temp_memory;
  6. }
  7. }
  8. //或
  9. void TestAutoPtr3() {
  10. std::auto_ptr<Simple> my_memory(new Simple(1));
  11. if (my_memory.get()) {
  12. my_memory.reset(); // 释放 my_memory 内部管理的内存
  13. }
  14. }

原来std::auto_ptrrelease()函数只是让出内存所有权,这显然也不符合 C++ 编程思想。

总结:std::auto_ptr
可用来管理单个对象的对内存,但是,请注意如下几点:

(1)尽量不要使用operator=。如果使用了,请不要再使用先前对象。
(2)记住release()函数不会释放对象,仅仅归还所有权。
(3)std::auto_ptr最好不要当成参数传递
(4)由于std::auto_ptroperator=问题,有其管理的对象不能放入std::vector等容器中。

由于std::auto_ptr引发了诸多问题,一些设计并不是非常符合C++编程思想,所以引发了下面 boost的智能指针,boost智能指针可以解决如上问题。

2、boost::scoped_ptr

boost::scoped_ptr属于 boost 库,定义在namespace boost中,包含头文件#include<boost/smart_ptr.hpp> 便可以使用。boost::scoped_ptrstd::auto_ptr 一样,可以方便的管理单个堆内存对象,特别的是,boost::scoped_ptr 独享所有权,避免了 std::auto_ptr 恼人的几个问题。

示例代码:

  1. void TestScopedPtr() {
  2. boost::scoped_ptr<Simple> my_memory(new Simple(1));
  3. if (my_memory.get()) {
  4. my_memory->PrintSomething();
  5. my_memory.get()->info_extend = "Addition";
  6. my_memory->PrintSomething();
  7. (*my_memory).info_extend += " other";
  8. my_memory->PrintSomething();
  9. my_memory.release();
  10. // 编译 error: scoped_ptr 没有 release 函数
  11. std::auto_ptr<Simple> my_memory2;
  12. my_memory2 = my_memory;
  13. // 编译 error: scoped_ptr 没有重载 operator=,不会导致所有权转移
  14. }
  15. }

首先,我们可以看到,boost::scoped_ptr 也可以像 auto_ptr 一样正常使用。但其没有 release() 函数,不会导致先前的内存泄露问题。其次,由于 boost::scoped_ptr 是独享所有权的,所以明确拒绝用户写my_memory2 = my_memory之类的语句,可以缓解 std::auto_ptr 几个恼人的问题。

由于 boost::scoped_ptr独享所有权,当我们真真需要复制智能指针时,需求便满足不了了,如此我们再引入一个智能指针,专门用于处理复制,参数传递的情况,这便是如下的 boost::shared_ptr

3、boost::shared_ptr

在上面我们看到 boost::scoped_ptr 独享所有权,不允许赋值、拷贝,boost::shared_ptr 是专门用于共享所有权的,由于要共享所有权,其在内部使用了引用计数。boost::shared_ptr 也是用于管理单个堆内存对象的。

实例代码:

  1. void TestSharedPtr(boost::shared_ptr<Simple> memory) {
  2. // 注意:无需使用 reference (或 const reference)
  3. memory->PrintSomething();
  4. std::cout << "TestSharedPtr UseCount: " << memory.use_count() << std::endl;
  5. }
  6. void TestSharedPtr2() {
  7. boost::shared_ptr<Simple> my_memory(new Simple(1));
  8. if (my_memory.get()) {
  9. my_memory->PrintSomething();
  10. my_memory.get()->info_extend = "Addition";
  11. my_memory->PrintSomething();
  12. (*my_memory).info_extend += " other";
  13. my_memory->PrintSomething();
  14. }
  15. std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
  16. TestSharedPtr(my_memory);
  17. std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
  18. //my_memory.release();// 编译 error: 同样,shared_ptr 也没有 release 函数
  19. }

执行结果为:
Simple: 1
PrintSomething:
PrintSomething: Addition
PrintSomething: Addition other
TestSharedPtr2 UseCount: 1
PrintSomething: Addition other
TestSharedPtr UseCount: 2
TestSharedPtr2 UseCount: 1
~Simple: 1

boost::shared_ptr 也可以很方便的使用。并且没有 release() 函数。关键的一点,boost::shared_ptr 内部维护了一个引用计数,由此可以支持复制、参数传递等。boost::shared_ptr 提供了一个函数 use_count() ,此函数返回 boost::shared_ptr 内部的引用计数。查看执行结果,我们可以看到在 TestSharedPtr2 函数中,引用计数为 1,传递参数后(此处进行了一次复制),在函数TestSharedPtr 内部,引用计数为2,在 TestSharedPtr 返回后,引用计数又降低为 1。当我们需要使用一个共享对象的时候,boost::shared_ptr 是再好不过的了。

4、boost::scoped_array

boost::scoped_array 是用于管理动态数组的。跟 boost::scoped_ptr 一样,也是独享所有权的。
示例代码:

  1. void TestScopedArray() {
  2. boost::scoped_array<Simple> my_memory(new Simple[2]);
  3. // 使用内存数组来初始化
  4. if (my_memory.get()) {
  5. my_memory[0].PrintSomething();
  6. my_memory.get()[0].info_extend = "Addition";
  7. my_memory[0].PrintSomething();
  8. (*my_memory)[0].info_extend += " other";
  9. // 编译 error,scoped_ptr 没有重载 operator*
  10. my_memory[0].release();
  11. // 同上,没有 release 函数
  12. boost::scoped_array<Simple> my_memory2;
  13. my_memory2 = my_memory;
  14. // 编译 error,同上,没有重载 operator=
  15. }
  16. }

boost::scoped_array 的使用跟 boost::scoped_ptr 差不多,不支持复制,并且初始化的时候需要使用动态数组。另外,boost::scoped_array 没有重载operator*,其实这并无大碍,一般情况下,我们使用 get() 函数更明确些。

5、boost::shared_array
由于 boost::scoped_array 独享所有权,显然在很多情况下(参数传递、对象赋值等)不满足需求,由此我们引入 boost::shared_array。跟 boost::shared_ptr 一样,内部使用了引用计数。

示例代码:

  1. void TestSharedArray(boost::shared_array<Simple> memory) {
  2. // 注意:无需使用 reference (或 const reference)
  3. std::cout << "TestSharedArray UseCount: " << memory.use_count() << std::endl;
  4. }
  5. void TestSharedArray2() {
  6. boost::shared_array<Simple> my_memory(new Simple[2]);
  7. if (my_memory.get()) {
  8. my_memory[0].PrintSomething();
  9. my_memory.get()[0].info_extend = "Addition 00";
  10. my_memory[0].PrintSomething();
  11. my_memory[1].PrintSomething();
  12. my_memory.get()[1].info_extend = "Addition 11";
  13. my_memory[1].PrintSomething();
  14. //(*my_memory)[0].info_extend += " other"; // 编译 error,scoped_ptr 没有重载 operator*
  15. }
  16. std::cout << "TestSharedArray2 UseCount: " << my_memory.use_count() << std::endl;
  17. TestSharedArray(my_memory);
  18. std::cout << "TestSharedArray2 UseCount: " << my_memory.use_count() << std::endl;
  19. }

执行输出:
Simple: 0
Simple: 0
PrintSomething:
PrintSomething: Addition 00
PrintSomething:
PrintSomething: Addition 11
TestSharedArray2 UseCount: 1
TestSharedArray UseCount: 2
TestSharedArray2 UseCount: 1
~Simple: 0
~Simple: 0

这几个智能指针(std::auto_ptrboost::scoped_ptrboost::shared_ptrboost::scoped_arrayboost::shared_array)已经基本够我们使用了,90% 的使用过标准智能指针的代码就这 5 种。

6、boost::weak_ptr
首先 boost::weak_ptr 是专门为 boost::shared_ptr 而准备的。有时候,我们只关心能否使用对象,并不关心内部的引用计数。boost::weak_ptrboost::shared_ptr 的观察者(Observer)对象,观察者意味着 boost::weak_ptr 只对 boost::shared_ptr 进行引用,而不改变其引用计数,当被观察的 boost::shared_ptr 失效后,相应的 boost::weak_ptr 也相应失效。

示例代码:

  1. void TestWeakPtr() {
  2. boost::weak_ptr<Simple> my_memory_weak;
  3. boost::shared_ptr<Simple> my_memory(new Simple(1));
  4. std::cout << "TestWeakPtr boost::shared_ptr UseCount: " << my_memory.use_count() << std::endl;
  5. my_memory_weak = my_memory;
  6. std::cout << "TestWeakPtr boost::shared_ptr UseCount: " << my_memory.use_count() << std::endl;
  7. }

执行结果为:
Simple: 1
TestWeakPtr boost::shared_ptr UseCount: 1
TestWeakPtr boost::shared_ptr UseCount: 1
~Simple: 1

我们看到,尽管被赋值了,内部的引用计数并没有什么变化

boost::weak_ptr 主要用在软件架构设计中,可以在基类(此处的基类并非抽象基类,而是指继承于抽象基类的虚基类)中定义一个 boost::weak_ptr,用于指向子类的 boost::shared_ptr,这样基类仅仅观察自己的 boost::weak_ptr 是否为空就知道子类有没对自己赋值了,而不用影响子类 boost::shared_ptr 的引用计数,用以降低复杂度,更好的管理对象。

7、boost::intrusive_ptr
讲完如上 6 种智能指针后,对于一般程序来说 C++ 堆内存管理就够用了,现在有多了一种 boost::intrusive_ptr,这是一种插入式的智能指针,内部不含有引用计数,需要程序员自己加入引用计数,不然编译不过(⊙﹏⊙b汗)。个人感觉这个智能指针没太大用处,至少我没用过。
可以参考:此篇博客


总结

如上讲了这么多智能指针,有必要对这些智能指针做个总结:

1、在可以使用 boost 库的场合下,拒绝使用 std::auto_ptr,因为其不仅不符合 C++ 编程思想,而且极容易出错。
2、在确定对象无需共享的情况下,使用 boost::scoped_ptr(当然动态数组使用 boost::scoped_array)。
3、在对象需要共享的情况下,使用 boost::shared_ptr(当然动态数组使用 boost::shared_array)。
4、在需要访问 boost::shared_ptr 对象,而又不想改变其引用计数的情况下,使用 boost::weak_ptr,一般常用于软件框架设计中。
5、最后一点,也是要求最苛刻一点:在你的代码中,不要出现 delete 关键字(或 C 语言的 free 函数),因为可以用智能指针去管理。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注