[英]How to take ownership of std::unique_ptr and std::shared_ptr
[英]Passing std::unique_ptr to constructor to take ownership
我想將std::unique_ptr
傳遞給一個類的構造函數,該類將獲取std::unique_ptr
擁有的數據的所有權。
下面的方法foo
和bar
在編譯器處理它們的方式方面是否有任何區別,從而使其中一種更可取?
foo
類:
template <class T>
class foo
{
std::unique_ptr<T> data_;
public:
foo(std::unique_ptr<T>&& data) :
data_{ std::forward<std::unique_ptr<T>>(data) }
{
}
};
bar
班:
template <class T>
class bar
{
std::unique_ptr<T> data_;
public:
bar(std::unique_ptr<T> data) :
data_{ std::move(data) }
{
}
};
綁定到引用只需少走一走:
void f(std::unique_ptr<T>&& p) { g(std::move(p)); }
f(std::make_unique<T>()); // no move, g binds directly to the temporary
綁定到對象參數需要一個實際步驟:
void f(std::unique_ptr<T> p) { g(std::move(p)); }
f(std::make_unique<T>()); // p constructed (= moved) from temporary,
// g binds to p
額外的動作包括一個指針副本,一個指向null的指針的設置以及一個帶有條件檢查的析構函數。 這並不是很大的代價,使用哪種樣式的問題取決於您編寫的代碼類型:
您的代碼葉子越多,使用的代碼就越少,帶有按值傳遞的簡單版本越能使您變得簡單。 相反,代碼的庫越多,對用戶的了解就越少,無論施加多小的開銷,其所具有的價值都不會增加。
你決定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.