C++智能指针

unique_ptr 

#include 
#include 
using namespace std;
int main()
{
    //智能指针unique_ptr  原始指针void* int* char*
    // 1. 在任意时刻,都只能有一个指针管理内存
    // 2. 在指针超出作用域时,会自动释放
    // 3. 指针类型不可拷贝,只可以move
    //    int num = 12;

    int* p = new int(100);
    //    *p = num;
    unique_ptr up = make_unique(*p); //使用make_unique
    //    unique_ptr up(p); //传入指针

    cout << *up << endl; //出了作用域自动销毁了
    cout << p << endl;
    cout << up.get() << endl;
    
}

shared_ptr

#include 
#include 
using namespace std;
int main()
{
    // shared_ptr 共享指针
    //可以共享数据
    //常量类型
    shared_ptr p = make_shared(10);
    //    shared_ptr pp = make_shared{new int(11)};
    //    cout << "value =" << pp << endl;
    cout << "value =" << p << endl;
    cout << "use count = " << p.use_count();
    shared_ptr pp = p; // copy
    cout << "p use count = " << p.use_count() << endl;
    cout << "pp use count = " << pp.use_count() << endl;
    *pp = 12; //两个都会发生改变
    cout << "p value =" << *p << endl;
    cout << "pp value =" << *pp << endl;
    //    pp = nullptr; //设置为null;会清理2不会清理1
    p = nullptr; //设置为null;会清理1不会清理2

    cout << "p use count = " << p.use_count() << endl;
    cout << "pp use count = " << pp.use_count() << endl;
    //自定义类型

    return 0;
}

不能将shared_ptr转为unique_ptr,但是可以将unique_ptr转为shared_ptr,通过std::move函数。

常见的设计

将你的函数返回unique_ptr是一种常见的设计模式,这样可以提高代码的复用度,你可以随时改变shared_ptr

#include 
#include 
using namespace std;

std::unique_ptr get_fun()
{
    //    cout << p << endl;
    unique_ptr p = make_unique(10);
    *p = 121212121;
    return p;
}
int main()
{
    unique_ptr p = make_unique(12);
    cout << "p.get()=" << p.get() << endl; //

    shared_ptr sp = move(p); //转换
    cout << "sp count = " << sp.use_count() << endl;
    cout << "p.get()=" << p.get() << endl; //不可以使用了

    shared_ptr sp3 = get_fun();
    if (sp3) {
        cout << "*sp3 = " << *sp3 << endl; //不可转换
        cout << "sp3.use_count()" << sp3.use_count() << endl;
        //        sp3.use_count();

    } else {
        cout << "error" << endl;
    }
    return 0;
}

weak_ptr

没有所有权,不能调用->和解引用*

C++智能指针_第1张图片

 

#include 
#include 
using namespace std;

std::unique_ptr get_fun()
{
    //    cout << p << endl;
    unique_ptr p = make_unique(10);
    *p = 121212121;
    return p;
}
int main()
{
    shared_ptr p = make_shared(122);
    weak_ptr wp(p);
    *p = 120;
    cout << "p value = " << *p << endl;
    shared_ptr pp = wp.lock(); //转为 共享指针

    cout << "pp value = " << *pp << endl;

    cout << "shared_prt count = " << p.use_count() << endl;
    cout << "wpak_prt count = " << wp.use_count() << endl;

    cout << " wp.expired= " << wp.expired() << endl;

    return 0;
}

你可能感兴趣的:(c++,算法,开发语言)