![](/img/trans.png)
[英]C++: Copy elision when passing std::unique_ptr (move-only type) rvalue as parameter
[英]C++ unique_ptr rvalue passing using std::move not working
error: call to implicitly-deleted copy of 'unique_ptr<Searchable>'
unique_ptr<Searchable> current(std::move(searchSpace.top()));
你好,
我試圖弄清楚為什么它不能編譯。 搜索空間是優先級隊列,我正在嘗試將右值searchSpace.top()移至新的當前對象。
奇怪的是,如果我將優先級隊列更改為deque:
unique_ptr<Searchable> current(std::move(Q.front()));
當Q為雙端隊列時,此方法工作正常。
那么,為什么后一個不起作用?
錯誤消息的其余部分:
copy constructor is implicitly deleted because 'unique_ptr<Searchable,
std::__1::default_delete<Searchable> >' has a user-declared move
constructor
_LIBCPP_INLINE_VISIBILITY unique_ptr(unique_ptr&& __u) _NOEXCEPT
std::priority_queue::top()
僅具有const
重載,返回const
引用。 這不能從。
另一方面, std::deque::front()
具有const和non-const重載,它們返回同等資格的引用。 您似乎正在使用非常量重載,其結果可以從中移出。
根據std :: priority_queue :: top()的文檔
const_reference top()const;
它返回const引用,通過std::move
將其轉換為const T &&
。 另一方面, const T &&
不會被std::unqiue_ptr
的移動ctor接受,因為它沒有這樣的重載,它只接受T &&
(不帶const
),請參閱std :: unqiue_ptr ctor的文檔。
關於為什么const引用被std::move
接受的原因,請參見此處為什么我們可以在const
對象上使用std::move
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.