C++智能指针 shared_ptr

C++智能指针 shared_ptr

  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\n", *sp3);
  auto sp4 = std::make_shared<std::string>("C++11");
  printf("sp4=%s\n", (*sp4).c_str());

 

成员函数

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

猜你喜欢

转载自blog.csdn.net/qq_40213457/article/details/80663881
今日推荐