美文网首页
智能指针

智能指针

作者: ClaireYuan_e78c | 来源:发表于2019-04-24 11:30 被阅读0次

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

相关文章

  • 目录

    智能指针(1) 智能指针(2) 智能指针(3) 智能指针之使用 容器 - vector(1) 容器 - vecto...

  • 智能指针到Android引用计数

    智能指针 LightRefBase RefBaseStrongPointerWeakPointer 智能指针 这是...

  • C++面试重点再梳理

    智能指针 请讲一下智能指针原理,并实现一个简单的智能指针 智能指针其实不是一个指针。它是一个用来帮助我们管理指针的...

  • C++研发工程师笔试题/面试题(1-10)

    1. (1) 简述智能指针的原理;(2)c++中常用的智能指针有哪些?(3)实现一个简单的智能指针。 简述智能指针...

  • 第十六章 string类和标准模板库(2)智能指针模板类

    (二)智能指针模板类 智能指针是行为类似指针的类对象,但这种对象还有其他便于管理内存的功能。 1.使用智能指针 (...

  • Rust for cpp devs - 智能指针

    与 cpp 类似,Rust 也有智能指针。Rust 中的智能指针与引用最大的不同是,智能指针 own 内存,而引用...

  • C++ 引用计数技术及智能指针的简单实现

    1.智能指针是什么 简单来说,智能指针是一个类,它对普通指针进行封装,使智能指针类对象具有普通指针类型一样的操作。...

  • 智能指针

    1. 什么是智能指针? 智能指针是行为类似于指针的类对象,但这种对象还有其他功能。 2. 为什么设计智能指针? 引...

  • chrome中智能指针使用

    chrom中智能指针的概述和作用 chrome中智能指针的用法和总结 包含如下四种智能指针:scoped_ptr ...

  • c++智能指针用法

    智能指针是什么 智能指针是c++中有四个智能指针:auto_ptr、shared_ptr、weak_ptr、uni...

网友评论

      本文标题:智能指针

      本文链接:https://www.haomeiwen.com/subject/nwpwgqtx.html