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;
}

  

  

原文地址:https://www.cnblogs.com/freebird92/p/9732210.html