[英]Should a constructor for a class that contains a move-only type receive the move-only type by reference or by rvalue reference?
[英]returning a move-only rvalue reference
在以下代碼中:
#include <memory>
struct C {
C() = default;
C(C const&) = delete;
C(C&&) = default;
int a;
};
C foo(C&& c) {
return c;
}
int main()
{
auto c = foo(C{});
}
我在foo
的return語句中出錯:
Use of deleted function 'C::C(const C&)'".
為什么要嘗試調用復制構造函數? 不應該使用移動構造函數,因為c
是右值引用? 即使不是因為這個原因,不應該return
語句總是調用移動構造函數,因為return
后值不能繼續使用?
內部函數foo
, c
,一個命名的東西,是一個左值。 要調用移動構造函數,您需要明確地使其看起來像一個右值
return std::move(c);
正如juanchopanza所指出的, c
是一個左值(因為它有一個名字)所以它會嘗試復制它。 雖然您可以利用事實,但是通過值傳遞的本地對象和函數參數可以被視為return語句中的rvalues,而不必在return語句中調用std::move
。 這讓你可以重寫這個功能
C foo(C c) {
return c;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.