【校招面试 之 C/C++】第26题 C++ 智能指针(二)之 share_ptr

1、综述 

shared_ptr 是一个标准的共享所有权的智能指针, 允许多个指针指向同一个对象. 定义在 memory 文件中(非memory.h), 命名空间为 std.

  shared_ptr 是为了解决 auto_ptr 在对象所有权上的局限性(auto_ptr 是独占的), 在使用引用计数的机制上提供了可以共享所有权的智能指针, 当然这需要额外的开销:
  (1) shared_ptr 对象除了包括一个所拥有对象的指针外, 还必须包括一个引用计数代理对象的指针.
  (2) 时间上的开销主要在初始化和拷贝操作上, *和->操作符重载的开销跟auto_ptr是一样.
  (3) 开销并不是我们不使用shared_ptr的理由, 永远不要进行不成熟的优化, 直到性能分析器告诉你这一点.

  使用方法:

可以使用模板函数 make_shared 创建对象, make_shared 需指定类型('<>'中)及参数('()'内), 传递的参数必须与指定的类型的构造函数匹配. 如:
  std::shared_ptr<int> sp1 = std::make_shared<int>(10);
  std::shared_ptr<std::string> sp2 = std::make_shared<std::string>("Hello c++");
也可以定义 auto 类型的变量来保存 make_shared 的结果.
  auto sp3 = std::make_shared<int>(11);
  printf("sp3=%d ", *sp3);
  auto sp4 = std::make_shared<std::string>("C++11");
  printf("sp4=%s ", (*sp4).c_str());

2、成员函数 

use_count 返回引用计数的个数
unique 返回是否是独占所有权( use_count 为 1)
swap 交换两个 shared_ptr 对象(即交换所拥有的对象)
reset 放弃内部对象的所有权或拥有对象的变更, 会引起原有对象的引用计数的减少
get 返回内部对象(指针), 由于已经重载了()方法, 因此和直接使用对象是一样的.如 shared_ptr<int> sp(new int(1)); sp 与 sp.get()是等价的

以下代码演示各个函数的用法与特点:

std::shared_ptr<int> sp0(new int(2));
            std::shared_ptr<int> sp1(new int(11));
            std::shared_ptr<int> sp2 = sp1;
            printf("%d
", *sp0);               // 2
            printf("%d
", *sp1);               // 11
            printf("%d
", *sp2);               // 11
            sp1.swap(sp0);
            printf("%d
", *sp0);               // 11
            printf("%d
", *sp1);               // 2
            printf("%d
", *sp2);               // 11

            std::shared_ptr<int> sp3(new int(22));
            std::shared_ptr<int> sp4 = sp3;
            printf("%d
", *sp3);               // 22
            printf("%d
", *sp4);               // 22
            sp3.reset();                        
            printf("%d
", sp3.use_count());    // 0
            printf("%d
", sp4.use_count());    // 1
            printf("%d
", sp3);                // 0
            printf("%d
", sp4);                // 指向所拥有对象的地址
            
            std::shared_ptr<int> sp5(new int(22));
            std::shared_ptr<int> sp6 = sp5;
            std::shared_ptr<int> sp7 = sp5;
            printf("%d
", *sp5);               // 22
            printf("%d
", *sp6);               // 22
            printf("%d
", *sp7);               // 22
            printf("%d
", sp5.use_count());    // 3
            printf("%d
", sp6.use_count());    // 3
            printf("%d
", sp7.use_count());    // 3
            sp5.reset(new int(33));                        
            printf("%d
", sp5.use_count());    // 1
            printf("%d
", sp6.use_count());    // 2
            printf("%d
", sp7.use_count());    // 2
            printf("%d
", *sp5);               // 33
            printf("%d
", *sp6);               // 22
            printf("%d
", *sp7);               // 22
       std::shared_ptr<int> sp1 = std::make_shared<int>(10);
            std::shared_ptr<int> sp2 = std::make_shared<int>(11);
            auto sp3 = sp2; 或 auto sp3(sp2);
            printf("sp1.use_count = %d
", sp1.use_count());  // 1
            printf("sp2.use_count = %d
", sp2.use_count());  // 2
            printf("sp3.use_count = %d
", sp3.use_count());  // 2
            sp3 = sp1;
            printf("sp1.use_count = %d
", sp1.use_count());  // 2
            printf("sp2.use_count = %d
", sp2.use_count());  // 1
            printf("sp3.use_count = %d
", sp3.use_count());  // 2

  

3、什么时候需要使用share_ptr

(1) 程序不知道自己需要使用多少对象. 如使用窗口类, 使用 shared_ptr 为了让多个对象能共享相同的底层数据.

(2) 程序不知道所需对象的准确类型.
(3) 程序需要在多个对象间共享数据.

4、使用share_ptr的注意事项:

(1) 禁止纯指针给智能指针赋值或者拷贝构造。 

int* a=new int(2);  
shared_ptr<int>sp=a;//  error  
sp=a;//    error 

(2)shared_ptr多次引用同一数据,会导致两次释放同一内存。如下:

{
int* pInt = new int[100];
shared_ptr<int> sp1(pInt);
// 一些其它代码之后…
shared_ptr<int> sp2(pInt);
}

(3)使用share_ptr造成循环引用

#include<iostream>
using namespace std;
 
struct Node
{
	shared_ptr<Node> _pre;
	shared_ptr<Node> _next;
 
	~Node()
	{
		cout << "~Node():" << this << endl;
	}
	int data;
};
 
void FunTest()
{
	shared_ptr<Node> Node1(new Node);
	shared_ptr<Node> Node2(new Node);
	Node1->_next = Node2;
	Node2->_pre = Node1;
 
	cout << "Node1.use_count:"<<Node1.use_count() << endl;      // 2
	cout << "Node2.use_count:"<< Node2.use_count() << endl;      //2
}
 
int main()
{
	FunTest();
	system("pause");
	return 0;
}

  

当出现上述问题时,有以下3种解决方法:

1️⃣当只剩下最后一个引用的时候需要手动打破循环引用释放对象。

2️⃣当parent的生存期超过children的生存期的时候,children改为使用一个普通指针指向parent。

3️⃣使用弱引用的智能指针(weak_ptr)打破这种循环引用。虽然这三种方法都可行,但方法1和方法2都需要程序员手动控制。

关于weak_ptr在下一篇文章中讲到。

参考:https://blog.csdn.net/man_sion/article/details/77196766

原文地址:https://www.cnblogs.com/xuelisheng/p/9350596.html