c++ - 在右值方法中从 *this 移动?

标签 c++ c++11 rvalue-reference

在 C++11 中,方法可以根据表示调用方法的对象的表达式是左值还是右值来重载。如果我从通过右值调用的方法返回 *this,我是否需要从 *this 显式地移动

Foo Foo::method() &&
{
    return std::move(*this);   // Is this move required or not?
}

不幸的是,我不能简单地在我的编译器上测试它,因为 g++ 还不支持这个特性:(

最佳答案

*this 的类型总是一个左值:

§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.

因此,如果您想调用移动构造函数,则需要 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(我知道的唯一实现引用限定符的编译器),我得到以下输出:

$ clang++ -std=c++0x -stdlib=libc++ -pedantic -Wall t.cpp
$ ./a.out
copy ctor // #1
move ctor // #2

关于c++ - 在右值方法中从 *this 移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3028632/

相关文章:

c++ - 在 "if" block 中分配字 rune 字

c++ - 如何使用 ESP8266-12E 通过 UDP 发送/接收

c++ - 初始化中的指针转换

c++ - C++中的统一随机数生成器

c++ - 插入/放置到位置已被占用的哈希表中

c++ - 为什么传递右值引用 (X&&) 就像传递左值引用 (X&)?

c++ - 构造对象的方法有什么区别

c++ - 了解勘误表中有关 EMC++ 第 41 项的评论

c++ - std::tuple::get 返回常量类型&&

recursion - 在函数定义中引用函数名称