• 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;
    }
  • 相关阅读:
    远程连接Oracle 服务器 解决Oracle查询中文乱码
    sql 复杂查询 以teacher student course多对多关系为例
    ZooKeeper 分布式锁实现
    zookeeper原理解析-客户端与服务器端交互
    zookeeper原理解析-服务器端处理流程
    zookeeper原理解析-选举
    zookeeper原理解析-序列化
    深入浅出 Redis client/server交互流程
    zookeeper原理解析-数据存储
    RocketMQ原理解析-Remoting
  • 原文地址:https://www.cnblogs.com/sssblog/p/11436539.html
Copyright © 2020-2023  润新知