Foo Foo::method() &&
{
return std::move(*this); // Is this move required or not?
}
不幸的是,我不能简单地测试这个在我的编译器,因为g不支持这个功能:(
解决方法
§9.3.2[class.this] p1
In the body of a non-static (9.3) member function,the keyword
thisis a prvalue expression whose value is the address of the object for which the function is called. The type ofthisin a member function of a classXisX*. […]
§5.3.1[expr.unary.op] p1
The unary
*operator performs indirection: the expression to which it is applied shall be a pointer to an object type,or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.
所以你需要std :: move如果你想调用move构造函数.
以下代码片段显示:
#include <iostream>
#include <utility>
struct test{
test(){}
test(test const&){ std::cout << "copy ctor // #1\n"; }
test(test&&){ std::cout << "move ctor // #2\n"; }
test f_no_move() &&{ return *this; }
test f_move() &&{ return std::move(*this); }
};
int main(){
test().f_no_move(); // #1
test().f_move(); // #2
}
使用Clang 3.1(我知道实现ref-qualifiers的唯一编译器),我得到以下输出:
$clang++ -std=c++0x -stdlib=libc++ -pedantic -Wall t.cpp $./a.out copy ctor // #1 move ctor // #2