[英]C++ Correct way to pass a std::unique_ptr object as reference on a function argument
我有一個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;
}
你不需要調用get
,只需要取消引用:
doSomething(*unique);
最好傳遞對存儲對象的引用,而不是通過引用傳遞std::unique_ptr
,因為對象的生存期和存儲不需要使用該對象傳遞給每個函數。
在解除引用指針時,標准庫智能指針應該像原始指針一樣使用。 也就是說,你只需使用
std::unique_ptr<Test> unique(new Test());
std::cout << unique->message << " John.\n";
doSomething(*unique);
我包含了聲明以顯示簡化用法和一個輸出以強調不使用std::endl
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.