一文掌握 C++ 智能指针的使用

开发 后端
C++11 引入了智能指针的概念,使用了引用计数的想法,让程序员不再需要关心手动释放内存。

[[422939]]

 RAII 与引用计数

了解 Objective-C/Swift 的程序员应该知道引用计数的概念。引用计数这种计数是为了防止内存泄露而产生的。

基本想法是对于动态分配的对象,进行引用计数,每当增加一次对同一个对象的引用,那么引用对象的引用计数就会增加一次, 每删除一次引用,引用计数就会减一,当一个对象的引用计数减为零时,就自动删除指向的堆内存。

在传统C++中,『记得』手动释放资源,总不是最佳实践。因为我们很有可能就忘记了去释放资源而导致泄露。所以通常的做法是对于一个对象而言,我们在构造函数的时候申请空间,而在析构函数(在离开作用域时调用)的时候释放空间, 也就是我们常说的 RAII 资源获取即初始化技术。

凡事都有例外,我们总会有需要将对象在自由存储上分配的需求,在传统 C++ 里我们只好使用 new 和 delete 去 『记得』对资源进行释放。而 C++11 引入了智能指针的概念,使用了引用计数的想法,让程序员不再需要关心手动释放内存。

这些智能指针就包括 std::shared_ptr std::unique_ptr std::weak_ptr,使用它们需要包含头文件<memory>。

注意:引用计数不是垃圾回收,引用计数能够尽快收回不再被使用的对象,同时在回收的过程中也不会造成长时间的等待, 更能够清晰明确的表明资源的生命周期。

std::shared_ptr

std::shared_ptr 是一种智能指针,它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显式的调用 delete,当引用计数变为零的时候就会将对象自动删除。

但还不够,因为使用 std::shared_ptr 仍然需要使用 new 来调用,这使得代码出现了某种程度上的不对称。

std::make_shared 就能够用来消除显式的使用 new,所以 std::make_shared 会分配创建传入参数中的对象, 并返回这个对象类型的 std::shared_ptr 指针。例如: 

  1. #include <iostream>  
  2. #include <memory>  
  3. void foo(std::shared_ptr<int> i)  
  4.  
  5.     (*i)++;  
  6.  
  7. int main()  
  8.  
  9.     // auto pointer = new int(10); // illegal, no direct assignment  
  10.     // Constructed a std::shared_ptr  
  11.     auto pointer = std::make_shared<int>(10);  
  12.     foo(pointer);  
  13.     std::cout << *pointer << std::endl; // 11  
  14.     // The shared_ptr will be destructed before leaving the scope  
  15.     return 0;  

std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数, 并通过 use_count() 来查看一个对象的引用计数。例如: 

  1. auto pointer = std::make_shared<int>(10);  
  2. auto pointerpointer2 = pointer; // 引用计数+1  
  3. auto pointerpointer3 = pointer; // 引用计数+1  
  4. int *p = pointer.get(); // 这样不会增加引用计数  
  5. std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 3  
  6. std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 3  
  7. std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 3  
  8. pointer2.reset();  
  9. std::cout << "reset pointer2:" << std::endl 
  10. std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 2  
  11. std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0, pointer2 已 reset  
  12. std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 2  
  13. pointer3.reset();  
  14. std::cout << "reset pointer3:" << std::endl 
  15. std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 1  
  16. std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0  
  17. std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 0, pointer3 已 reset 

std::unique_ptr

std::unique_ptr 是一种独占的智能指针,它禁止其他智能指针与其共享同一个对象,从而保证代码的安全: 

  1. std::unique_ptr<int> pointer = std::make_unique<int>(10); // make_unique 从 C++14 引入  
  2. std::unique_ptr<int> pointerpointer2 = pointer; // 非法 

make_unique 并不复杂,C++11 没有提供 std::make_unique,可以自行实现: 

  1. template<typename T, typename ...Args>  
  2. std::unique_ptr<T> make_unique( Args&& ...args ) {  
  3.   return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );  

至于为什么没有提供,C++ 标准委员会主席 Herb Sutter 在他的博客中提到原因是因为『被他们忘记了』。

既然是独占,换句话说就是不可复制。但是,我们可以利用 std::move 将其转移给其他的 unique_ptr,例如: 

  1. #include <iostream>  
  2. #include <memory>  
  3. struct Foo {  
  4.     Foo() { std::cout << "Foo::Foo" << std::endl; }  
  5.     ~Foo() { std::cout << "Foo::~Foo" << std::endl; }  
  6.     void foo() { std::cout << "Foo::foo" << std::endl; }  
  7. };  
  8. void f(const Foo &) {  
  9.     std::cout << "f(const Foo&)" << std::endl 
  10.  
  11. int main() {  
  12.     std::unique_ptr<Foo> p1(std::make_unique<Foo>());  
  13.     // p1 不空, 输出  
  14.     if (p1) p1->foo();  
  15.     {  
  16.         std::unique_ptr<Foo> p2(std::move(p1));  
  17.         // p2 不空, 输出  
  18.         f(*p2);  
  19.         // p2 不空, 输出  
  20.         if(p2) p2->foo();  
  21.         // p1 为空, 无输出  
  22.         if(p1) p1->foo();  
  23.         p1 = std::move(p2);  
  24.         // p2 为空, 无输出  
  25.         if(p2) p2->foo();  
  26.         std::cout << "p2 被销毁" << std::endl 
  27.     }  
  28.     // p1 不空, 输出  
  29.     if (p1) p1->foo();  
  30.     // Foo 的实例会在离开作用域时被销毁  

std::weak_ptr

如果你仔细思考 std::shared_ptr 就会发现依然存在着资源无法释放的问题。看下面这个例子: 

  1. struct A;  
  2. struct B;  
  3. struct A {  
  4.     std::shared_ptr<B> pointer;  
  5.     ~A() {  
  6.         std::cout << "A 被销毁" << std::endl 
  7.     }  
  8. };  
  9. struct B {  
  10.     std::shared_ptr<A> pointer;  
  11.     ~B() {  
  12.         std::cout << "B 被销毁" << std::endl 
  13.     }  
  14. };  
  15. int main() {  
  16.     auto a = std::make_shared<A>();  
  17.     auto b = std::make_shared<B>();  
  18.     a->pointer = b 
  19.     b->pointer = a 

运行结果是 A, B 都不会被销毁,这是因为 a,b 内部的 pointer 同时又引用了 a,b,这使得 a,b 的引用计数均变为了 2,而离开作用域时,a,b 智能指针被析构,却只能造成这块区域的引用计数减一。

这样就导致了 a,b 对象指向的内存区域引用计数不为零,而外部已经没有办法找到这块区域了,也就造成了内存泄露,如图 1:

图 1

解决这个问题的办法就是使用弱引用指针 std::weak_ptr,std::weak_ptr是一种弱引用(相比较而言 std::shared_ptr 就是一种强引用)。

弱引用不会引起引用计数增加,当换用弱引用时候,最终的释放流程如图 2 所示:

图 2

在上图中,最后一步只剩下 B,而 B 并没有任何智能指针引用它,因此这块内存资源也会被释放。

std::weak_ptr 没有 * 运算符和 -> 运算符,所以不能够对资源进行操作,它的唯一作用就是用于检查 std::shared_ptr 是否存在,其 expired() 方法能在资源未被释放时,会返回 false,否则返回 true。

总结

智能指针这种技术并不新奇,在很多语言中都是一种常见的技术,现代 C++ 将这项技术引进,在一定程度上消除了 new/delete 的滥用,是一种更加成熟的编程范式。 

 

责任编辑:庞桂玉 来源: C语言与C++编程
相关推荐

2010-12-17 10:07:59

2010-02-05 14:36:20

C++智能指针

2023-11-17 11:48:08

智能指针C++

2023-12-20 12:40:51

C++RAII编程

2010-01-28 13:57:19

C++指针基础

2024-02-01 11:57:31

this指针代码C++

2024-01-24 11:44:44

C++智能指针开发

2022-12-20 07:39:46

2023-12-21 17:11:21

Containerd管理工具命令行

2010-01-27 14:18:41

Android智能指针

2021-05-12 18:22:36

Linux 内存管理

2023-12-29 15:30:41

内存存储

2011-07-01 14:28:47

Qt 指针

2015-07-27 11:34:03

Linux内核指针

2022-10-21 17:24:34

契约测试定位

2023-07-04 08:56:07

指针类型Golang

2021-09-07 05:02:50

C++ConstexprConst

2023-10-24 11:44:21

2024-03-01 16:43:48

C++11智能指针内存

2018-12-29 16:40:29

c语言编程语言指针
点赞
收藏

51CTO技术栈公众号