unique_ptr 和 shared_ptr

首先

unique_ptr 和 shared_ptr 两个都是智能指针,意味着它们会自动释放它们无法再引用该对象时指向的对象 。

 

unique_ptr

使用unique_ptr时,最多只能让unique_ptr指向一个资源 。因为unique_ptr任何资源只能有一个 。

 并且unique_ptr 不能有多个副本 unique_ptr ,所以任何复制a的尝试unique_ptr都会导致编译时错误 。

当它unique_ptr被销毁时,资源会自动回收 。

#include <memory>

std::unique_ptr<T> myPtr(new T);        // Okay

std::unique_ptr<T> myOtherPtr = myPtr;  // Error: Can't copy unique_ptr


/********* 但是,unique_ptr可转移指针使用权 *********/


std::unique_ptr<T> myPtr(new T);                    // Okay

std::unique_ptr<T> myOtherPtr = std::move(myPtr);   // Okay ,myPtr不再指向原来的资源
#include <iostream>
#include <memory>

int main()
{
   #if 0
     std::unique_ptr<int> myPtr(new int(5));    //声明一个unique_ptr智能指针,new了新对象并且给指针赋值
     std::unique_ptr<int> myPtr2;               //仅仅是声明一个unique_ptr智能指针

     std::cout << *myPtr << std::endl;          //打印出5
     std::cout << *myPtr2 << std::endl;         //出现段错误

  #else

     std::unique_ptr<int> myPtr(new int(5));    //声明一个unique_ptr智能指针,并且给它赋值
     std::unique_ptr<int> myPtr2;               //声明一个unique_ptr智能指针
     myPtr2 = std::move(myPtr);                 //转移指针使用权

     std::cout << *myPtr2 << std::endl;         //打印出5
     std::cout << *myPtr << std::endl;          //出现段错误
  
  #endif

  return 0;
}

shared_ptr

shared_ptr另一方面,允许多个指针指向给定资源 。当shared_ptr资源的最后一个被销毁时,资源将被释放 。

#include <memory>

std::shared_ptr<T> myPtr(new T);        // Okay

std::shared_ptr<T> myOtherPtr = myPtr;  // Okay,shared_ptr指针可以被赋值



/********* 但是,unique_ptr 可转移指针使用权 *********/


std::shared_ptr<T> myPtr(new T);                    // Okay

std::shared_ptr<T> myOtherPtr = std::move(myPtr);   // Okay ,myPtr也同样不再指向原来的资源


/*********** unique_ptr 共享指针指向的资源 ************/

  std::shared_ptr<int> myPtr(new int(5));    //声明一个unique_ptr智能指针,并且给它赋值
  std::shared_ptr<int> myPtr2;               //声明一个unique_ptr智能指针
  myPtr2.reset(myPtr.get());                 //.get()是获取指针

  std::cout << *myPtr2 << std::endl;         //打印出5
  std::cout << *myPtr << std::endl;          //打印出5

 

简而言之

使用unique_ptr时您需要一个指针时单指针被销毁,将被回收的对象 。

shared_ptr当您想要多个指向同一资源的指针时使用 。

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值