zoukankan      html  css  js  c++  java
  • c++11 智能指针

    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;
    }
  • 相关阅读:
    java 的 CopyOnWriteArrayList类
    AtomicInteger类的简单应用
    关于java的关键字 transient
    关于ArrayList的一些源码分析
    Eclipse新建java类的时候,自动创建注释
    关于spring-data-jpa的排序问题
    hibernate CascadeType属性
    springBoot框架不同环境读取不同的配置文件
    你迷茫的原因在于读书太少而想的太多!!!
    学历是铜牌,能力是银牌,人脉是金牌,思维是王牌
  • 原文地址:https://www.cnblogs.com/sssblog/p/11436539.html
Copyright © 2011-2022 走看看