加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C在函数参数上传递std :: unique_ptr对象作为引用的正确方法

发布时间:2020-12-16 10:36:05 所属栏目:百科 来源:网络整理
导读:我有一个std :: unique_ptr T对象和图书馆功能,需要T作为参数.此函数将更改T对象数据. 传递std :: unique_ptr T的更好方法是什么?那个功能?以上代码是否正确?有更好的方法吗? #include iostream#include string#include memoryclass Test { public: std:
我有一个std :: unique_ptr< T>对象和图书馆功能,需要T&作为参数.此函数将更改T对象数据.

传递std :: unique_ptr< T>的更好方法是什么?那个功能?以上代码是否正确?有更好的方法吗?

#include <iostream>
#include <string>
#include <memory>

class Test {

   public: 
       std::string message = "Hi";
};

void doSomething(Test& item)
{
    item.message = "Bye";
}

int main()
{
     std::unique_ptr<Test> unique = std::unique_ptr<Test>(new Test());

     std::cout << unique->message << " John." << std::endl;

     doSomething(*unique.get());

     std::cout << unique->message << " John." << std::endl;
}

解决方法

在解除引用指针时,标准库智能指针应该像原始指针一样使用.也就是说,你只需使用

std::unique_ptr<Test> unique(new Test());
std::cout << unique->message << " John.n";
doSomething(*unique);

我在声明中加入了简化用法和一个输出来强调not to use std::endl.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读