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

时间:2015-12-03 10:34:34

标签: c++ c++11 unique-ptr

我有一个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;
}

2 个答案:

答案 0 :(得分:8)

You don't need to call get, just dereference:

doSomething(*unique);

It is best to pass around references to the stored object rather than passing the std::unique_ptr around by reference, as the lifetime and storage of an object shouldn't need to be communicated to every function using that object.

答案 1 :(得分:5)

标准库智能指针在取消引用指针时应该像原始指针一样使用。也就是说,您只需使用

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

我包含声明以显示简化用法和一个输出以强调not to use std::endl