[英]Returning pointer by value does not move the object
我用vs2011編譯了這段代碼。 它打印第一個構造函數然后復制構造函數 。 但是如果我改變函數返回a而不是ap ,它將移動對象。 這是一個錯誤還是為什么它會像這樣? * ap不是rvalue嗎?
struct A
{
A() { cout << "constructor" << endl;}
A(const A&) { cout << "copy constructor " << endl;}
void operator=(const A&) { cout << "assignment operator" << endl; }
A( A&&) { cout << "move copy constructor" << endl;}
void operator=(A&&) { cout << "move assignment operator" << endl;}
};
A func() { A a; A *ap = &a; return *ap; }
int main()
{
A a = func();
return 0;
}
*ap
是左值(§5.3.1.1,n3290),對於自動發生的移動通常是不安全的。 局部變量return a;
是一個不同的情況 。 編譯器無需證明在此特定情況下它是安全的。 這是在你不真正想要指針語義的情況下不使用指針的另一個好理由。
將其更改為:
return std::move(*ap);
會導致它被明確地移動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.