![](/img/trans.png)
[英]“Use of deleted function” when calling `std::unique_ptr` move constructor?
[英]“error: use of deleted function” when calling std::move on unique_ptr in move constructor
#include <memory>
class A
{
public:
A()
{
}
A( const A&& rhs )
{
a = std::move( rhs.a );
}
private:
std::unique_ptr<int> a;
};
此代碼將無法使用g ++ 4.8.4進行編譯,並引發以下錯誤:
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>
::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_de
lete<int>]’
a = std::move( rhs.a );
^
我知道unique_ptr的副本構造函數和副本分配構造函數已刪除且無法調用,但是我認為通過在此處使用std::move
,我將改為調用移動分配構造函數。 官方文檔甚至顯示了這種分配類型。
我沒有看到的代碼有什么問題?
A( const A&& rhs )
// ^^^^^
刪除const
從對象移出是破壞性的,因此不能從const
對象移出是很公平的。
當我沒有明確聲明移動構造函數和復制構造函數時,我也遇到了這個錯誤。
我使用了https://en.cppreference.com/w/cpp/language/move_assignment中的示例,但是當我嘗試實現移動分配運算符時
A& operator=(A&& other){...}
沒有實現兩個核心
A(const A& o) : s(os) { ... } A(A&& o) : s(std::move(os)) { }
嘗試使用移動分配時,對std :: move的調用未編譯,並且出現了此確切錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.