unique_ptr函数调用

unique_ptr函数调用
#include <iostream>
#include <memory>
#include "cat.h"
void do_with_cat_pass_value(std::unique_ptr<cat> c){
    c->cat_info();
}
void do_with_cat_pass_ref(std::unique_ptr<cat> &c){
    c->cat_info();
    c->set_name("dd");
    c->cat_info();
    c.reset();
}
void do_with_cat_pass_ref_const(const std::unique_ptr<cat> &c){
    c->cat_info();
    c->set_name("dd");
    c->cat_info();
    //  c.reset(); //加了const之后不能reset()
}
std::unique_ptr<cat> get_unique_ptr(){
    std::unique_ptr<cat> p_dog=std::make_unique<cat>("Local cat");
    std::cout<<"unique ptr address: "<<p_dog.get()<<std::endl;//unique ptr address: 0x1f7e3d51b40
    std::cout<<"unique ptr address: "<<&p_dog<<std::endl;//unique ptr address: 0x9c491ff8c8
    return p_dog;
}

using namespace std;

int main(){
//    std::unique_ptr<cat> c1= std::make_unique<cat>("aa");
//    //1. pass by value:
//    //do_with_cat_pass_value(c1); //报错,所有权问题
//    do_with_cat_pass_value(std::move(c1)); //cat name: aa, destructor of cat: aa
//        //调用完直接析构
//    // c1->cat_info();//编译能过,但是执行出错
//    do_with_cat_pass_value(make_unique<cat> ("bb") ); //cat name: bb, destructor of cat: bb
//        // 1.隐式转换move  2.调用完直接析构

//    //2. pass by ref
//    std::unique_ptr<cat> c2=std::make_unique<cat>("cc");
//    //2.1 不加const:
//    do_with_cat_pass_ref(c2);//cat name: cc  cat name: dd
//        //destructor of cat:
//        // 如果调用的函数中没有 reset(), destructor发生在整个程序运行结束之后
//        //如果有,reset()之后就destructor,
//    //c2->cat_info(); //reset()之后不能cat_info()

//    //2.2 加const,不能在ref函数中reset
//    std::unique_ptr<cat> c3=std::make_unique<cat>("ff");
//    do_with_cat_pass_ref_const (c3);//cat name: ff  cat name: dd
//    c3->cat_info();//cat name: dd
//        //destructor发生在整个程序运行结束之后
//    cout<<"-----over-----------"<<endl;

    //链式
    get_unique_ptr()->cat_info();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值