C++正确地将std::unique_ptr对象作为函数参数传递的方式

3

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

5
“*unique”足够了。 - Jarod42
2个回答

11

你不需要调用get,只需解除引用:

doSomething(*unique);

最好传递指向存储对象的引用,而不是通过引用传递std::unique_ptr。因为不需要将对象的生命周期和存储通知给使用该对象的每个函数。


6
标准库的智能指针在解引用指针时应该像原始指针一样使用。也就是说,您只需使用
std::unique_ptr<Test> unique(new Test());
std::cout << unique->message << " John.\n";
doSomething(*unique);

我包含了这个声明以展示简化使用和一个输出来强调不要使用std::endl


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接