std::unique_ptr使用

1 引言

std::unique_ptrc++11起引入的智能指針,為什么必須要在c++11起才有該特性,主要還是c++11增加了move語義,否則無法對(duì)對(duì)象的所有權(quán)進(jìn)行傳遞。

2 示例代碼

#include <memory>
#include <iostream>
#include <utility>

class Foo{

public:
    Foo() = default;
    Foo(int a):_a(a) {}
    ~Foo() {}
    int get_a(){
        return _a;
    }
    void set_a(int a) {
        _a = a;
    }
private:
    int _a;

};

std::unique_ptr<Foo> change_a(std::unique_ptr<Foo> f)
{
    f->set_a(10);
    return f;
}

int main()
{
    // std::make_unique是c++14才有
    std::unique_ptr<Foo> pf = std::make_unique<Foo>(10);
    // unique_ptr的復(fù)制構(gòu)造函數(shù)和拷貝構(gòu)造函數(shù)是刪除了的,這樣保證了對(duì)象獨(dú)占,如果不是獨(dú)占,那么跟shared_ptr
    // 就是一樣的功能了。
    // std::unique_ptr<Foo> pf1 = pf;  // compile error

    // 按值傳參,會(huì)有拷貝問題,同上
    // auto p = change_a(pf);   //compile error

    auto p = change_a(std::move(pf));
    std::cout << "get_a = " << p->get_a() << std::endl;
    if(!pf)
    {
        std::cout << "pf is nullptr" << std::endl;
    }
    //owner transfer from function
    std::unique_ptr<Foo> pf2 = std::make_unique<Foo>(11);
    std::unique_ptr<Foo> p2 = change_a(std::move(pf2));
    std::cout << "get_a = " << p2->get_a() << std::endl;
    if(!pf2)
    {
        std::cout << "pf2 is nullptr" << std::endl;
    }

    //使用reset
    pf2.reset(new Foo(12));
    std::cout << "pf2 is not null: " << pf2->get_a() <<  std::endl;

    //release獲取原始指針
    Foo* ff = pf2.release();
    if(!pf2)
    {
        std::cout << "pf2 is nullptr" << std::endl;
    }
    std::cout << "ff is not null: " << ff->get_a() <<  std::endl;

    return 0;
}

備注

  1. std::make_unique是c++14才有的特性
  2. 返回值是右值操作,所以不需要std::move
  3. std::unique_ptr禁止對(duì)象拷貝和復(fù)制,否則無關(guān)管理對(duì)象。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容