在右值方法中从* this移动? [英] Move from *this in an rvalue method?
问题描述
在C ++ 11中,方法可以重载是否表示调用方法的对象的表达式是左值或右值。如果从通过右值调用的方法中返回 * this
,我需要从<$ c $>中显式地移动 move
c> * this 还是不是?
Foo Foo :: method()&&
{
return std :: move(* this); //是否需要这个移动吗?不幸的是,我不能简单地在我的编译器上测试这个,因为g ++不是这样的。支持此功能:(
解决方案 * this
的类型总是:
§9.3.2[class.this] p1
在非静态(9.3)成员函数的正文中,关键字 this
是一个prvalue表达式,其值是调用函数的对象的地址。 this
X
类的成员函数中的 X *
strong>。[...]
§5.3.1[expr.unary.op] / code>
一元 *
操作符执行间接:应用它的表达式应为指向对象类型的指针,或指向函数类型的指针,结果为左值
所以你需要 std :: move
以下代码片段显示:
#include< iostream>
#include< utility>
struct test {
test(){}
test(test const&){std :: cout< copy ctor //#1\\\
; }
test(test&&){std :: cout<< move ctor //#2\\\
; }
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
In C++11, methods can be overloaded on whether or not the expression that denotes the object on which the method is called is an lvalue or an rvalue. If I return *this
from a method called via an rvalue, do I need to explicitly move
from *this
or not?
Foo Foo::method() &&
{
return std::move(*this); // Is this move required or not?
}
Unfortunately, I can't simply test this on my compiler since g++ does not support this feature yet :(
解决方案 The type of *this
is always an lvalue:
§9.3.2 [class.this] p1
In the body of a non-static (9.3) member function, the keyword this
is a prvalue expression whose value is the address of the object for which the function is called. The type of this
in a member function of a class X
is X*
. [...]
§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.
So you will need to std::move
if you want to invoke the move constructor.
The following code snippet shows that:
#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
}
Using Clang 3.1 (the only compiler I know that implements ref-qualifiers), I get the following output:
$ clang++ -std=c++0x -stdlib=libc++ -pedantic -Wall t.cpp
$ ./a.out
copy ctor // #1
move ctor // #2
这篇关于在右值方法中从* this移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!