2012-11-28 29 views
3

我已经用vs2011编译了这段代码。它首先打印构造函数然后复制构造函数。 但是,如果我更改函数返回a而不是ap,它将移动该对象。这是一个错误还是为什么它的行为如此? * ap不是右值吗?按值返回指针不会移动对象

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; 
} 

回答

6

*ap是一个左值(第5.3.1.1,n3290),它一般不是安全的移动自动发生。本地变量return a;different case。编译器没有要求证明在这个特定的情况下它是安全的。这是在不真正需要指针语义的情况下不使用指针的另一个好理由。

将其更改为:

return std::move(*ap); 

将导致它不过是明确移动。

+1

安** xvalue ** !?突然间,我感到非常失去联系。感谢您的链接。 – NPE