什么是"*this的右值参考"?

Ral*_*zky 24 c++ rvalue-reference c++11

"标准还为成员函数调用参考限定符"的最常见用例是"用于*this的rvalue引用"?

顺便说一句,有关于这个语言功能一个很好的解释在这里.

And*_*zos 21

调用时,每个成员函数都有一个*this引用的隐式对象参数.

那么(a)这些正常的函数重载:

void f(const T&);
void f(T&&);
Run Code Online (Sandbox Code Playgroud)

当被称为f(x); (b)这些成员函数重载:

struct C
{
    void f() const &;
    void f() &&;
};
Run Code Online (Sandbox Code Playgroud)

当调用时x.f()- (a)和(b)调度具有相似的可行性和排名.

因此用例基本相同.它们是支持移动语义优化.在rvalue成员函数中,您基本上可以掠夺对象资源,因为您知道它是一个即将到期的对象(即将被删除):

int main()
{
    C c;
    c.f(); // lvalue, so calls lvalue-reference member f
    C().f(); // temporary is prvalue, so called rvalue-reference member f
    move(c).f(); // move changes c to xvalue, so again calls rvalue-reference member f
}
Run Code Online (Sandbox Code Playgroud)

例如:

struct C
{
    C operator+(const C& that) const &
    {
        C c(*this); // take a copy of this
        c += that;
        return c;
    }

    C operator+(const C& that) &&
    {
        (*this) += that;
        return move(*this); // moving this is ok here
    }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*ely 5

当调用rvalues时,某些操作可以更有效,因此在值类别上重载*this允许自动使用最有效的实现,例如

struct Buffer
{
  std::string m_data;
public:
  std::string str() const& { return m_data; }        // copies data
  std::string str()&& { return std::move(m_data); }  // moves data
};
Run Code Online (Sandbox Code Playgroud)

(这种优化可以完成std::ostringstream,但尚未正式提出AFAIK.)

调用rvalues时有些操作没有意义,因此重载*this允许删除rvalue表单:

struct Foo
{
  void mutate()&;
  void mutate()&& = delete;
};
Run Code Online (Sandbox Code Playgroud)

我还没有真正需要使用这个功能,但是我可能会发现它有更多用途,因为我关心的两个编译器都支持它.