在 C++11 中,可以根据表示调用方法的对象的表达式是左值还是右值来重载方法。如果我*this
从通过右值调用的方法返回,我是否需要显式地move
从*this
或不需要?
Foo Foo::method() &&
{
return std::move(*this); // Is this move required or not?
}
不幸的是,我不能简单地在我的编译器上测试它,因为 g++ 还不支持这个特性:(
在 C++11 中,可以根据表示调用方法的对象的表达式是左值还是右值来重载方法。如果我*this
从通过右值调用的方法返回,我是否需要显式地move
从*this
或不需要?
Foo Foo::method() &&
{
return std::move(*this); // Is this move required or not?
}
不幸的是,我不能简单地在我的编译器上测试它,因为 g++ 还不支持这个特性:(
的类型*this
始终是左值:
§9.3.2 [class.this] p1
在非静态 (9.3) 成员函数的主体中,关键字
this
是纯右值表达式,其值是调用该函数的对象的地址。类的this
成员函数中的类型X
是X*
。[...]
§5.3.1 [expr.unary.op] p1
一元运算
*
符执行间接:应用它的表达式应该是指向对象类型的指针,或指向函数类型的指针,结果是一个左值,指向表达式指向的对象或函数。
std::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