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;
    }
  • 相关阅读:
    EOF ---shell编程
    Linux错误代码含义
    linux连接sybase数据库-isql
    CH7-WEB开发(集成在一起)
    [转]ASP.NET MVC 入门10、Action Filter 与 内置的Filter实现(实例-防盗链)
    [转]ASP.NET MVC 入门9、Action Filter 与 内置的Filter实现(介绍)
    [转]ASP.NET MVC 入门8、ModelState与数据验证
    [转]ASP.NET MVC 入门7、Hellper与数据的提交与绑定
    [转]ASP.NET MVC 入门6、TempData
    [转]ASP.NET MVC 入门5、View与ViewData
  • 原文地址:https://www.cnblogs.com/sssblog/p/11436539.html
Copyright © 2011-2022 走看看