首页 > 编程语言 > 详细

c++11 智能指针

时间:2019-08-30 19:07:02      阅读:54      评论:0      收藏:0      [点我收藏+]

unique_ptr, shared_ptr 以及weak_ptr

1. example

#include <memory>
#include <iostream>

using namespace std;

int main() {
  unique_ptr<int> up1(new int(11));
  unique_ptr<int> up2 = up1;  //不能通过编译

  cout << *up1 << endl;

  unique_ptr<int> up3 = move(up1); //up3是唯一的unique_ptr只能指针

  cout << *up3 << endl;
  cout << *up1 << endl;  //运行时错误

  up3.reset(); //显示内存释放
  up1.reset(); //不会导致运行时错误
  cout << *up3 << endl;  //运行时错误

  shared_ptr<int> sp1(new int(22));
  shared_ptr<int> sp2 = sp1;

  cout << *sp1 << endl;
  cout << *sp2 << endl;

  sp1.reset();
  cout << *sp2 << endl;

  return 0;
}

unique_ptr 与所指对象的内存绑定紧密,不能与其他unique_ptr类型的指针对象共享所值对象的内存。up2不能分享up1的所有权。这种所有权只能通过move()函数来转移。

shared_ptr允许多个指针共享同一内存,实现上采用了引用计数,一旦一个shared_ptr指针放弃了所有权,其他的shared_ptr对对象的引用并不会受到影响。

weak_ptr可以指向shared_ptr指针指向的对象内存,却并不拥有该内存。而使用weak_ptr的成员lock,则可返回其指向内存的一个shared_ptr对象,且在该对象内存已经无效时,返回指针控制。

2. weak_ptr

#include <memory>
#include <iostream>

using namespace std;

void Check(weak_ptr<int>& wp) {
  shared_ptr<int> sp = wp.lock();
  if (sp != nullptr) {
    cout << "still " << *sp << endl;
  } else {
    cout << "pointer is invalid" << endl;
  }
}

int main() {
  shared_ptr<int> sp1(new int(22));
  shared_ptr<int> sp2 = sp1;
  weak_ptr<int> wp = sp1;

  cout << *sp1 << endl;
  cout << *sp2 << endl;
  Check(wp);  //still 22

  sp1.reset();
  cout << *sp2 << endl;
  Check(wp);  //still 22

  sp2.reset();
  Check(wp);  //pointer is invalid

  return 0;
}

 

c++11 智能指针

原文:https://www.cnblogs.com/sssblog/p/11436539.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!