簡體   English   中英

阻止移動unique_ptr C ++ 11

[英]Prevent moving of a unique_ptr C++11

有沒有辦法阻止用戶明確獲取一個唯一指針的所有權

 std::move

使它成為const

unique_ptr move構造函數采用非const rvalue引用,因此不能使用const對象調用。

const unique_ptr<int> owner(new int);
// ...
unique_ptr<int> thief = std::move(owner);  // ERROR

這允許使用unique_ptr ,就像boost::scoped_ptr

通過返回std::unique_ptr ,您已放棄對象的控制。 新的所有者要么將其銷毀,要么將其傳遞給其他人。

如果您不打算讓用戶釋放該對象,則返回一個引用。

你有boost::scoped_ptr / const std::unique_ptr (參見Jonathan的回答),它在技術上回答你的問題 - 調用者發布,但不能泄露資源 - 但我沒有看到一個令人信服的例子,為什么你需要這個而是std::unique_ptr或引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM