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

     
    #include <iostream>
    #include <typeinfo>
    #include <type_traits>
    #include <memory>
    using namespace std;
    // 智能指针 -> 一个指向带计数的内存的变量
    // unique_ptr 任何时刻内存只有一个拥有者
    // share_ptr 每次添加引用,计数加1
    // weak_ptr, 仅简单指向,不计数;在使用lock后, 尝试返回share_ptr, 无效返回 nullptr
    
    void Check(weak_ptr<int> & wp){
        shared_ptr<int> sp = wp.lock();
        if (sp != nullptr)
            cout << "still " << *sp << "   " << sp.use_count() <<endl;
        else
            cout << "pointer is invalid." <<endl;
    }
    
    int main()
    {
        shared_ptr<int> sp1 (new int(99)); //绑定动态对象
        shared_ptr<int> sp2 = sp1;
        weak_ptr<int> wp = sp1; // 指向share_ptr<int>所批对象
        
        cout << *sp1 << "  " << sp1.use_count() << endl;
        cout << *sp2 << "  " << sp2.use_count() << endl;
        Check(wp);
        
        sp1.reset();
        cout << *sp2 << "  " << sp2.use_count() << endl;
        Check(wp);
        
        sp2.reset();
        Check(wp);
        
        unique_ptr<int> up1(new int(11)); // 无法复制的unique_ptr
        //unique_ptr<int> up2 = up1;       // 无法通过编译
        cout << *up1 <<endl;            // 11
        
        unique_ptr<int> up3 = move(up1); // 现在up3是数据唯一的unique_ptr智能指针
        cout << *up3 <<endl;
        //cout << *up1 <<endl; // 运行时错误
        up3.reset();           // 显式释放内存
        up1.reset();           // 不会导致运行时错误
        system("pause");
        return 0;
    }
    

      

      

  • 相关阅读:
    入门学习嵌入式260期手把手配套视频7个项目实战送书
    使用from 的setTimeOut方法实现定时关闭Form
    C#面试题
    《JS语法字典》网友总结
    简单SQL语句小结
    面试前的简历
    Hello World的17种写法(C#)(转贴)
    张芸京 偏爱
    关于我对.setTmp()的理解及应用
    VS 2005使用技巧
  • 原文地址:https://www.cnblogs.com/freebird92/p/9732210.html
Copyright © 2011-2022 走看看