search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of C++ smart pointers

C++ Smart Pointer Detailed Explanation


##1. Introduction

Since the C++ language does not have an automatic memory recycling mechanism, programmers must use new memory every time. Manually delete. It is not uncommon for programmers to forget to delete, the process is too complicated, and ultimately there is no delete, and exceptions cause the program to exit prematurely without executing delete.

Using smart pointers can effectively alleviate such problems. This article mainly explains the usage of smart pointers. Including: std::auto_ptr, boost::scoped_ptr, boost::shared_ptr, boost::scoped_array, boost::shared_array, boost::weak_ptr, boost::intrusive_ptr. You may be thinking, are so many smart pointers really necessary to solve the new and delete matching problems? After reading this article, I think you will naturally have the answer in your mind.

The following will explain the above 7 types of smart pointers (smart_ptr) in order.

2. Specific use


1. Summary

For the compiler, a smart pointer is actually a stack object, not Pointer type, when the life of the stack object is about to end, the smart pointer releases the heap memory managed by it through the destructor. All smart pointers are overloaded with the "operator->" operator, which directly returns a reference to the object and is used to operate the object. The original method of accessing smart pointers uses the "." operator.

To access the raw pointer contained in the smart pointer, you can use the get() function. Since a smart pointer is an object, if (my_smart_object) is always true. To determine whether the raw pointer of the smart pointer is null, you need to determine like this: if (my_smart_object.get()).

The smart pointer includes the reset() method. If no parameters are passed (or NULL is passed), the smart pointer will release the currently managed memory. If an object is passed, the smart pointer will release the current object to manage the newly passed in object.


We write a test class to assist analysis:

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: " << info_extend.c_str() << std::endl;
  }
  std::string info_extend;
  int number;
};


2, std::auto_ptr


std::auto_ptr belongs to STL. Of course, it can be used in namespace std by including the header file #include. std::auto_ptr can conveniently manage a single heap memory object.


Let’s start with the code analysis:

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


##The execution result is:

Simple: 1
PrintSomething:
PrintSomething: Addition
PrintSomething: Addition other
~Simple: 1


The above is the code for normal use of std::auto_ptr. Everything seems to be fine. In any case, we don't need to use the damn delete explicitly.


In fact, the good times did not last long. Let’s take a look at another example below:

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


In the end, the above code caused a crash , the above code is absolutely in line with C++ programming ideas, but it actually crashes. After following the source code of std::auto_ptr, we see that the culprit is "my_memory2 = my_memory". With this line of code, my_memory2 completely takes over the memory management of my_memory. ownership, causing my_memory to be dangling, causing a crash when last used.


So, when using std::auto_ptr, you must not use the "operator=" operator. As a library, users are not allowed to use it, and it is not explicitly rejected [1], which is somewhat unexpected.


After reading the first example of std::auto_ptr that did not last long, let us look at another one:

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


The execution result is:

Simple: 1

Did you see any exception? The object we created was not destructed and "~Simple: 1" was not output, resulting in a memory leak. When we don't want my_memory to continue to survive, we call the release() function to release the memory, but the result is a memory leak (in a memory-limited system, if my_memory takes up too much memory, we will consider returning it immediately after use is completed, and Instead of waiting until my_memory ends its life, it will be returned).



The correct code should be:

void TestAutoPtr3() {
  std::auto_ptr<Simple> my_memory(new Simple(1));
  if (my_memory.get()) {
    Simple* temp_memory = my_memory.release();
    delete temp_memory;
  }
}


or

void TestAutoPtr3() {
  std::auto_ptr<Simple> my_memory(new Simple(1));
  if (my_memory.get()) {
    my_memory.reset();  // 释放 my_memory 内部管理的内存
  }
}


It turns out that the release() function of std::auto_ptr only gives up memory ownership, which is obviously not in line with C++ programming ideas.

Summary: std::auto_ptr can be used to manage the memory of a single object. However, please pay attention to the following points:

(1) Try not to use "operator=". If used, do not reuse the previous object.

(2) Remember that the release() function does not release the object, but only returns ownership.

(3) std::auto_ptr is best not to be passed as a parameter (readers can write their own code to determine why not).

(4) Due to the "operator=" problem of std::auto_ptr, objects managed by it cannot be put into containers such as std::vector.

(5) ……


There are so many restrictions on using a std::auto_ptr. It cannot be used to manage heap memory arrays. This should be What are you thinking about now? I also think there are quite a lot of restrictions. One day, if you are not careful, it will cause problems.


Because std::auto_ptr has caused many problems, some designs are not very consistent with C++ programming ideas, so the following boost smart pointers have been triggered. Boost smart pointers can solve the above problems. question.


Let’s continue looking down.


3. boost::scoped_ptr

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


我们还是从代码开始分析:

void TestScopedPtr() {
  boost::scoped_ptr<Simple> my_memory(new Simple(1));
  if (my_memory.get()) {
    my_memory->PrintSomething();
    my_memory.get()->info_extend = "Addition";
    my_memory->PrintSomething();
    (*my_memory).info_extend += " other";
    my_memory->PrintSomething();
  
    my_memory.release();           // 编译 error: scoped_ptr 没有 release 函数
    std::auto_ptr<Simple> my_memory2;
    my_memory2 = my_memory;        // 编译 error: scoped_ptr 没有重载 operator=,不会导致所有权转移
  }
}


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


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


4、boost::shared_ptr


boost::shared_ptr 属于 boost 库,定义在 namespace boost 中,包含头文件 #include 便可以使用。在上面我们看到 boost::scoped_ptr 独享所有权,不允许赋值、拷贝,boost::shared_ptr 是专门用于共享所有权的,由于要共享所有权,其在内部使用了引用计数。boost::shared_ptr 也是用于管理单个堆内存对象的。


我们还是从代码开始分析:

void TestSharedPtr(boost::shared_ptr<Simple> memory) {  // 注意:无需使用 reference (或 const reference)
  memory->PrintSomething();
  std::cout << "TestSharedPtr UseCount: " << memory.use_count() << std::endl;
}
void TestSharedPtr2() {
  boost::shared_ptr<Simple> my_memory(new Simple(1));
  if (my_memory.get()) {
    my_memory->PrintSomething();
    my_memory.get()->info_extend = "Addition";
    my_memory->PrintSomething();
    (*my_memory).info_extend += " other";
    my_memory->PrintSomething();
  }
  std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
  TestSharedPtr(my_memory);
  std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
  //my_memory.release();// 编译 error: 同样,shared_ptr 也没有 release 函数
}


执行结果为:

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 是再好不过的了。


在此,我们已经看完单个对象的智能指针管理,关于智能指针管理数组,我们接下来讲到。


5、boost::scoped_array


boost::scoped_array 属于 boost 库,定义在 namespace boost 中,包含头文件 #include 便可以使用。


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


我们还是从代码开始分析:

void TestScopedArray() {
      boost::scoped_array<Simple> my_memory(new Simple[2]); // 使用内存数组来初始化
      if (my_memory.get()) {
        my_memory[0].PrintSomething();
        my_memory.get()[0].info_extend = "Addition";
        my_memory[0].PrintSomething();
        (*my_memory)[0].info_extend += " other";            // 编译 error,scoped_ptr 没有重载 operator*
        my_memory[0].release();                             // 同上,没有 release 函数
        boost::scoped_array<Simple> my_memory2;
        my_memory2 = my_memory;                             // 编译 error,同上,没有重载 operator=
      }
}


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


下面肯定应该讲 boost::shared_array 了,一个用引用计数解决复制、参数传递的智能指针类。


6、boost::shared_array


boost::shared_array 属于 boost 库,定义在 namespace boost 中,包含头文件 #include 便可以使用。


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


我们还是从代码开始分析:

void TestSharedArray(boost::shared_array<Simple> memory) {  // 注意:无需使用 reference (或 const reference)
  std::cout << "TestSharedArray UseCount: " << memory.use_count() << std::endl;
}
void TestSharedArray2() {
  boost::shared_array<Simple> my_memory(new Simple[2]);
  if (my_memory.get()) {
    my_memory[0].PrintSomething();
    my_memory.get()[0].info_extend = "Addition 00";
    my_memory[0].PrintSomething();
    my_memory[1].PrintSomething();
    my_memory.get()[1].info_extend = "Addition 11";
    my_memory[1].PrintSomething();
    //(*my_memory)[0].info_extend += " other";  // 编译 error,scoped_ptr 没有重载 operator*
  }
  std::cout << "TestSharedArray2 UseCount: " << my_memory.use_count() << std::endl;
  TestSharedArray(my_memory);
  std::cout << "TestSharedArray2 UseCount: " << my_memory.use_count() << std::endl;
}


执行结果为:

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


跟 boost::shared_ptr 一样,使用了引用计数,可以复制,通过参数来传递。


至此,我们讲过的智能指针有 std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array。这几个智能指针已经基本够我们使用了,90% 的使用过标准智能指针的代码就这 5 种。可如下还有两种智能指针,它们肯定有用,但有什么用处呢,一起看看吧。


7、boost::weak_ptr


boost::weak_ptr 属于 boost 库,定义在 namespace boost 中,包含头文件 #include 便可以使用。


在讲 boost::weak_ptr 之前,让我们先回顾一下前面讲解的内容。似乎 boost::scoped_ptr、boost::shared_ptr 这两个智能指针就可以解决所有单个对象内存的管理了,这儿还多出一个 boost::weak_ptr,是否还有某些情况我们没纳入考虑呢?


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


我们还是从代码开始分析:

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


执行结果为:

Simple: 1
TestWeakPtr boost::shared_ptr UseCount: 1
TestWeakPtr boost::shared_ptr UseCount: 1
~Simple: 1


我们看到,尽管被赋值了,内部的引用计数并没有什么变化,当然,读者也可以试试传递参数等其他情况。

现在要说的问题是,boost::weak_ptr 到底有什么作用呢?从上面那个例子看来,似乎没有任何作用,其实 boost::weak_ptr 主要用在软件架构设计中,可以在基类(此处的基类并非抽象基类,而是指继承于抽象基类的虚基类)中定义一个 boost::weak_ptr,用于指向子类的 boost::shared_ptr,这样基类仅仅观察自己的 boost::weak_ptr 是否为空就知道子类有没对自己赋值了,而不用影响子类 boost::shared_ptr 的引用计数,用以降低复杂度,更好的管理对象。


8、boost::intrusive_ptr

boost::intrusive_ptr属于 boost 库,定义在 namespace boost 中,包含头文件 #include 便可以使用。

讲完如上 6 种智能指针后,对于一般程序来说 C++ 堆内存管理就够用了,现在有多了一种 boost::intrusive_ptr,这是一种插入式的智能指针,内部不含有引用计数,需要程序员自己加入引用计数,不然编译不过(⊙﹏⊙b汗)。个人感觉这个智能指针没太大用处,至少我没用过。有兴趣的朋友自己研究一下源代码哦J。


三、总结

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

1、在可以使用 boost 库的场合下,拒绝使用 std::auto_ptr,因为其不仅不符合 C++ 编程思想,而且极容易出错[2]。

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 函数),因为可以用智能指针去管理。

以上就是C++ 智能指针详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Windows 11 系统下的五款最佳免费 C++ 编译器推荐Windows 11 系统下的五款最佳免费 C++ 编译器推荐Apr 23, 2023 am 08:52 AM

C++是一种广泛使用的面向对象的计算机编程语言,它支持您与之交互的大多数应用程序和网站。你需要编译器和集成开发环境来开发C++应用程序,既然你在这里,我猜你正在寻找一个。我们将在本文中介绍一些适用于Windows11的C++编译器的主要推荐。许多审查的编译器将主要用于C++,但也有许多通用编译器您可能想尝试。MinGW可以在Windows11上运行吗?在本文中,我们没有将MinGW作为独立编译器进行讨论,但如果讨论了某些IDE中的功能,并且是DevC++编译器的首选

C++报错:变量未初始化,应该如何解决?C++报错:变量未初始化,应该如何解决?Aug 21, 2023 pm 10:01 PM

在C++程序开发中,当我们声明了一个变量但是没有对其进行初始化,就会出现“变量未初始化”的报错。这种报错经常会让人感到很困惑和无从下手,因为这种错误并不像其他常见的语法错误那样具体,也不会给出特定的代码行数或者错误类型。因此,下面我们将详细介绍变量未初始化的问题,以及如何解决这个报错。一、什么是变量未初始化错误?变量未初始化是指在程序中声明了一个变量但是没有

C++编译错误:未定义的引用,该怎么解决?C++编译错误:未定义的引用,该怎么解决?Aug 21, 2023 pm 08:52 PM

C++是一门广受欢迎的编程语言,但是在使用过程中,经常会出现“未定义的引用”这个编译错误,给程序的开发带来了诸多麻烦。本篇文章将从出错原因和解决方法两个方面,探讨“未定义的引用”错误的解决方法。一、出错原因C++编译器在编译一个源文件时,会将它分为两个阶段:编译阶段和链接阶段。编译阶段将源文件中的源码转换为汇编代码,而链接阶段将不同的源文件合并为一个可执行文

如何优化C++开发中的文件读写性能如何优化C++开发中的文件读写性能Aug 21, 2023 pm 10:13 PM

如何优化C++开发中的文件读写性能在C++开发过程中,文件的读写操作是常见的任务之一。然而,由于文件读写是磁盘IO操作,相对于内存IO操作来说会更为耗时。为了提高程序的性能,我们需要优化文件读写操作。本文将介绍一些常见的优化技巧和建议,帮助开发者在C++文件读写过程中提高性能。使用合适的文件读写方式在C++中,文件读写可以通过多种方式实现,如C风格的文件IO

C++编译错误:无法为类模板找到实例化,应该怎么解决?C++编译错误:无法为类模板找到实例化,应该怎么解决?Aug 21, 2023 pm 08:33 PM

C++是一门强大的编程语言,它支持使用类模板来实现代码的复用,提高开发效率。但是在使用类模板时,可能会遭遇编译错误,其中一个比较常见的错误是“无法为类模板找到实例化”(error:cannotfindinstantiationofclasstemplate)。本文将介绍这个问题的原因以及如何解决。问题描述在使用类模板时,有时会遇到以下错误信息:e

iostream头文件的作用是什么iostream头文件的作用是什么Mar 25, 2021 pm 03:45 PM

iostream头文件包含了操作输入输出流的方法,比如读取一个文件,以流的方式读取;其作用是:让初学者有一个方便的命令行输入输出试验环境。iostream的设计初衷是提供一个可扩展的类型安全的IO机制。

C++中的信号处理技巧C++中的信号处理技巧Aug 21, 2023 pm 10:01 PM

C++是一种流行的编程语言,它强大而灵活,适用于各种应用程序开发。在使用C++开发应用程序时,经常需要处理各种信号。本文将介绍C++中的信号处理技巧,以帮助开发人员更好地掌握这一方面。一、信号处理的基本概念信号是一种软件中断,用于通知应用程序内部或外部事件。当特定事件发生时,操作系统会向应用程序发送信号,应用程序可以选择忽略或响应此信号。在C++中,信号可以

c++数组怎么初始化c++数组怎么初始化Oct 15, 2021 pm 02:09 PM

c++初始化数组的方法:1、先定义数组再给数组赋值,语法“数据类型 数组名[length];数组名[下标]=值;”;2、定义数组时初始化数组,语法“数据类型 数组名[length]=[值列表]”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool