左侧的右值 [英] rvalue on the left side

查看:94
本文介绍了左侧的右值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要编译此代码?我以为ctor返回的右值不在内存中,因此不能用作左值。

Why is this code compiling? I thought that rvalues returned by ctor are not located in memory and therefore can't be used as lvalues.

#include <iostream>
#include <vector>

class Y {
public :
    explicit Y(size_t num = 0)
    : m_resource {std::vector<int>(num)}
    {
    }

    std::vector<int> m_resource;
};

int main(int argc, const char * argv[]) {
    Y(1) = Y(0); // WHAT?!?
    return 0;
}


推荐答案

已声明综合赋值运算符作为其中之一(如果可以合成并且未声明为已删除),请参见12.8 [class.copy]第18段:

The synthesized assignment operator is declared as one of these (if it can be synthesized and isn't declared as deleted) according to see 12.8 [class.copy] paragraph 18:


  • Y& Y :: operator =(Y const&)

  • Y& Y :: operator =(Y&)()

  • Y& Y::operator=(Y const&)
  • Y& Y::operator=(Y&) ()

也就是说,就像其他任何成员函数一样 ref-qualifiers

That is, like for any other member function which isn't specifically declared with ref-qualifiers it is applicable to rvalues.

如果要防止赋值左侧的临时对象,则需要相应地声明它:

If you want to prevent a temporary object on the left hand side of the assignment you'd need to declare it correspondingly:

class Y {
public :
    explicit Y(std::size_t num = 0);
    Y& operator= (Y const&) & = default;
};

标准为<$ c $使用名称​​ ref-qualifier c>和之前的 =默认值。相关建议为 N2439 。我不知道在哪里有 ref-qualifiers 的详细描述。在此问题中有一些信息。

The standard uses the name ref-qualifier for the & before the = default. The relevant proposal is N2439. I don't know where there is a good description of ref-qualifiers. There is some information at this question.

这篇关于左侧的右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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