【问题标题】:About assigning values to functions关于为函数赋值
【发布时间】:2021-06-13 07:10:09
【问题描述】:

我有以下代码sn-p:

#include <iostream>
using namespace std;


class X {
int i;
public:
    X(int ii = 0);
    void modify();
};

X::X(int ii) { i = ii; }
void X::modify() { i++; }

X f5() {   return X(); }
const X f6() {   return X(); }

void f7(X& x) {
  x.modify();
}

int f()
{
    return 18;
}
int main() {
  f5() = X(1);          /// Why does this work??? Isn't f5() an rvalue ??? (*)
  f5().modify();
///  f7(f5());          /// cannot bind non-const lvalue reference of type 'X&' to an rvalue of type X; not contradictory with (*)?
//!  f6() = X(1);
//!  f6().modify();
//!  f7(f6());
//! f() = 12; this also doesn't work
  return 0;
}

f5() = X() 如何工作? f5() 不是右值吗?那为什么f() = 12 不起作用?有什么不同 ?另外,f7(f5()) 生成的错误并不是说f5() 是右值?我错过了什么?

【问题讨论】:

    标签: c++ assign rvalue


    【解决方案1】:

    f5() 确实产生一个右值,f5() = X(1); 调用隐式生成的移动 operator =。如果删除此运算符,它将停止工作:void operator =(X &amp;&amp;) = delete;

    f7(f5()) 生成的错误也确实表明f5() 是一个右值:

    到 X 类型的右值

    【讨论】:

    • 但这和f() = 12有什么区别?
    • 不同之处在于f() 产生一个内置的原始int 类型。对这种类型的赋值要求左操作数是左值。
    • 需要明确的是,删除移动分配可以防止这种情况,但它也会阻止其他事情的工作。要专门禁用此行为,您可以&amp;-qualify 复制和移动作业。
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2014-02-17
    • 2021-05-10
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多