智能指针

2019-04-24  本文已影响0人  ClaireYuan_e78c

std::unique_ptr<>

初始化:直接初始化、右值赋值、std::move
作为函数返回值
作为函数形参

#include <iostream>
using namespace std;
class Base{
public:
    Base(int val=0) : val_(val){
        cout << "Base ctor  " << val_ << "\n"; 
    }
    ~Base()
    {
        cout << "------------------------Base dctor  " << val_ << "\n"; 
    }

    void GetVal()
    {
        cout << "val is " << val_;
        cout << "\n\n";
    }
private:
    int val_;
};

std::unique_ptr<Base> GetBase(int n){
    std::unique_ptr<Base> base;
    base.reset(new Base(n));
    return std::move(base);
}

int main(){
    
    //std::unique_ptr<Base> pBase(std::move(GetBase()));
    //auto pBase = GetBase();
    //unique_ptr初始化:直接初始化、右值赋值、std::move
    std::unique_ptr<Base> pBase1(new Base(1));
    std::unique_ptr<Base> pBase2(new Base(2));


    //unique_ptr是返回值
    std::unique_ptr<Base> pBase3;
    pBase3 = GetBase(44);
    pBase1 = GetBase(55);
    //pBase3 = std::unique_ptr<Base>(new Base(3)); //rvalue

    std::unique_ptr<Base> pBase4;
    pBase4 = std::move(pBase1);  //std::move

    Base* base = pBase1.get();

    //unique_ptr作为形参,一般是通过std::move移交转移权

    //unique_ptr release():释放指针独占权,返回指向对象的指针,并将内部指针设为null
    //unique_ptr reset():释放指针独占权,回收对象内存,无返回值
    base = pBase2.release();
    delete base;
    Base *base2 = pBase2.get();

    //pBase2 = std::move(pBase1);
    //pBase1.reset(pBase2.get());
    
}
上一篇下一篇

猜你喜欢

热点阅读