欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

std::shared_ptr 详解

程序员文章站 2024-02-29 09:37:52
...

一、介绍

shared_ptr是一种智能指针(smart pointer),作用有如同指针,但会记录有多少个shared_ptrs共同指向一个对象。这便是所谓的引用计数(reference counting)。
一旦最后一个这样的指针被销毁,也就是一旦某个对象的引用计数变为0,这个对象会被自动删除。

二、shared_ptr的构造和析构

#include <iostream>
#include <memory>

struct C {int* data;};

int main () {
 auto deleter = [](int*p){
    std::cout << "[deleter called]\n"; delete p;
  };//Labmbda表达式

  std::shared_ptr<int> p1;//默认构造,没有获取任何指针的所有权,引用计数为0
  std::shared_ptr<int> p2 (nullptr);//同1
  std::shared_ptr<int> p3 (new int);//拥有指向int的指针所有权,引用计数为1
  std::shared_ptr<int> p4 (new int, deleter);//作用同3,但是拥有自己的析构方法,如果指针所指向对象为复杂结构C
                                    //结构C里有指针,默认析构函数不会将结构C里的指针data所指向的内存释放,这时需要自己使用自己的析构函数(删除器)
  std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());//同4,但拥有自己的分配器(构造函数),如成员中有指针,可以为指针分配内存,原理跟浅拷贝和深拷贝类似
  std::shared_ptr<int> p6 (p5);//如果p5引用计数为0,则引用计数加1,否则同样为0
  std::shared_ptr<int> p7 (std::move(p6));//获取p6的引用计数,p6引用计数为0
  std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));//p8获取所有权,引用计数设置为1
  std::shared_ptr<C> obj (new C);
  std::shared_ptr<int> p9 (obj, obj->data);//同6一样,只不过拥有自己的删除器与4一样

  std::cout << "use_count:\n";
  std::cout << "p1: " << p1.use_count() << '\n';
  std::cout << "p2: " << p2.use_count() << '\n';
  std::cout << "p3: " << p3.use_count() << '\n';
  std::cout << "p4: " << p4.use_count() << '\n';
  std::cout << "p5: " << p5.use_count() << '\n';
  std::cout << "p6: " << p6.use_count() << '\n';
  std::cout << "p7: " << p7.use_count() << '\n';
  std::cout << "p8: " << p8.use_count() << '\n';
  std::cout << "p9: " << p9.use_count() << '\n';
  return 0;
}
/*
Output:
use_count:
p1: 0
p2: 0
p3: 1
p4: 1
p5: 2
p6: 0
p7: 2
p8: 1
p9: 2
*/

三、shared_ptr赋值

给shared_ptr赋值有三种方式,如下

#include <iostream>
#include <memory>

int main () {
  std::shared_ptr<int> foo;
  std::shared_ptr<int> bar (new int(10));

  foo = bar;                          // 拷贝,引用计数加1

  bar = std::make_shared<int> (20);   // 移动
//unique_ptr 不共享它的指针。它无法复制到其他 unique_ptr,无法通过值传递到函数,也无法用于需要副本的任何标准模板库 (STL) 算法。只能移动unique_ptr
  std::unique_ptr<int> unique (new int(30));
  foo = std::move(unique);            // move from unique_ptr,引用计数转移

  std::cout << "*foo: " << *foo << '\n';
  std::cout << "*bar: " << *bar << '\n';

  return 0;
}
Output:
/*
*foo: 30
*bar: 20
*/

四、成员函数功能

1、swap:交换内存
void swap (shared_ptr& x)

  std::shared_ptr<int> foo (new int(10));
  std::shared_ptr<int> bar (new int(20));

  foo.swap(bar);//此时foo和bar所指向的内存发生交换

2、reset:引用计数减1,并可以重新赋值
void reset()

  std::shared_ptr<int> sp;  // 

  sp.reset (new int);       // 获取指针的所有权
  *sp=10;
  std::cout << *sp << '\n';

  sp.reset (new int);       // 之前的指针的引用计数减1,并获取当前指针的所有权
  *sp=20;
  std::cout << *sp << '\n';

  sp.reset();  //引用计数减1,释放内存

3、get:获取原始指针
element_type* get();

// shared_ptr::get example
#include <iostream>
#include <memory>

int main () {
  int* p = new int (10);
  std::shared_ptr<int> a (p);

  if (a.get()==p)
    std::cout << "a and p point to the same location\n";

  // three ways of accessing the same address:
  std::cout << *a.get() << "\n";    //10
  std::cout << *a << "\n";        //10
  std::cout << *p << "\n";        //10

  return 0;
}

4、use_count:获取引用计数值,共享指针为空返回0
long int use_count();

5、unique :检测是否唯一
bool unique :

#include <iostream>
#include <memory>

int main () {
  std::shared_ptr<int> foo;
  std::shared_ptr<int> bar (new int);

  std::cout << "foo unique?\n" << std::boolalpha;

  std::cout << "1: " << foo.unique() << '\n';  // false (empty)

  foo = bar;
  std::cout << "2: " << foo.unique() << '\n';  // false (shared with bar)

  bar = nullptr;
  std::cout << "3: " << foo.unique() << '\n';  // true

  return 0;
}

6、make_shared:构造共享指针
shared_ptr make_shared (Args&&… args);

#include <iostream>
#include <memory>

int main () {

  std::shared_ptr<int> foo = std::make_shared<int> (10);
  // same as:
  std::shared_ptr<int> foo2 (new int(10));

  auto bar = std::make_shared<int> (20);//创建内存,并返回共享指针,只创建一次内存,make_shared详细原理可以看其他博客

  auto baz = std::make_shared<std::pair<int,int>> (30,40);

  std::cout << "*foo: " << *foo << '\n';
  std::cout << "*bar: " << *bar << '\n';
  std::cout << "*baz: " << baz->first << ' ' << baz->second << '\n';

  return 0;
}

7、static_pointer_cast:转换指针类型
template <class T, class U>
shared_ptr static_pointer_cast (const shared_ptr& sp)

#include <iostream>
#include <memory>

struct A {
  static const char* static_type;
  const char* dynamic_type;
  A() { dynamic_type = static_type; }
};
struct B: A {
  static const char* static_type;
  B() { dynamic_type = static_type; }
};

const char* A::static_type = "class A";
const char* B::static_type = "class B";

int main () {
  std::shared_ptr<A> foo;
  std::shared_ptr<B> bar;

  foo = std::make_shared<A>();

  // cast of potentially incomplete object, but ok as a static cast:
  //bar = std::static_pointer_cast<B>(foo);//父类转子类,强制转换,没有进行类型检查
 //foo = std::dynamic_pointer_cast<A>(bar);//子类转父类,动态转换,进行了类型检查


  std::cout << "foo's static  type: " << foo->static_type << '\n';
  std::cout << "foo's dynamic type: " << foo->dynamic_type << '\n';
  std::cout << "bar's static  type: " << bar->static_type << '\n';
  std::cout << "bar's dynamic type: " << bar->dynamic_type << '\n';

  return 0;
}
Output:
foo's static  type: class A
foo's dynamic type: class A
bar's static  type: class B
bar's dynamic type: class A