什么是“这个”的右值引用。对于? [英] What are "rvalue references for *this" for?

查看:117
本文介绍了什么是“这个”的右值引用。对于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是rvalue references for * this的最典型的用例,标准还调用成员函数的引用限定符?



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

解决方案

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

所以(a)这些正常的函数重载:

  void f(const T&); 
void f(T&&);当调用 f(x)时,



<和(b)这些成员函数重载:

  struct C 
{
void f ;;
void f()&& ;;
};调用 xf()时,



(a)和(b)具有类似的可行性和排名。



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

  int main()
{
C c;
c.f(); // lvalue,所以调用lvalue-reference成员f
C()。f(); // temporary是prvalue,所以称为rvalue-reference member f
move(c).f(); //将更改c移动到xvalue,因此再次调用rvalue-reference成员f
}

例如:

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

C运算符+(const C& that)&&
{
(* this)+ = that;
return move(* this); // move this is ok here
}
}


What are the most typical use cases of "rvalue references for *this" which the standard also calls reference qualifiers for member functions?

By the way, there is a really good explanation about this language feature here.

解决方案

When called, each member function has an implicit object parameter that *this references.

So (a) these normal function overloads:

void f(const T&);
void f(T&&);

when called like f(x); and (b) these member function overloads:

struct C
{
    void f() const &;
    void f() &&;
};

when called like x.f() - both (a) and (b) dispatch with similar viability and ranking.

So the use cases are essentially the same. They are to support move semantic optimization. In the rvalue member function you can essentially pillage the objects resources because you know that it is an expiring object (is about to be deleted):

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
}

So for example:

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
    }
}

这篇关于什么是“这个”的右值引用。对于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆