C ++函数返回一个右值,但是可以分配一个新值? [英] C++ function returns a rvalue, but that can be assigned a new value?

查看:115
本文介绍了C ++函数返回一个右值,但是可以分配一个新值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

 #include <iostream>
 using namespace std;

 class A {

 };

 A rtByValue() {
return A();
 }

 void passByRef(A &aRef) {
    // do nothing
 }

 int main() {
    A aa;
    rtByValue() = aa;            // compile without errors
    passByRef(rtByValue());      // compile with error 

    return 0;
 }

g ++编译器出现以下错误:

The g++ compiler gives the following error:

d.cpp: In function ‘int main()’:
d.cpp:19:23: error: invalid initialization of non-const reference of type ‘A&’ from an rvalue of type ‘A’
d.cpp:12:6: error: in passing argument 1 of ‘void passByRef(A&)’

它说我不能传递一个rvalue作为一个非const引用的参数,但我困惑的是为什么我

It says that I can't pass an rvalue as an argument of a non-const reference, but what I'm confused about is why I can assign to this rvalue, just as the code shows.

推荐答案

传递右值 rtByValue / code>到期望一个左值引用的函数不工作,因为这将需要左值引用参数从右值初始化。 §8.5.3/ 5描述了如何初始化lvalue引用–我不会全部引用它,但它基本上说可以从另一个左值引用初始化一个左值引用

Passing the rvalue rtByValue() to a function that expects an lvalue reference doesn't work because this would require the lvalue reference argument to be initialized from an rvalue. §8.5.3/5 describes how lvalue references can be initialized – I won't quote it in full, but it basically says that an lvalue reference can be initialized


    < >
  • 或者可以转换为中间类型

  • 或右值的左值引用,但只有当我们初始化的左值引用是const-引用

由于我们需要初始化的参数不是const引用,所以这一切都不适用。

Since the argument we need to initialize is not a const-reference, none of this applies.

另一方面,

rtByValue() = aa; 

即,分配给临时对象是可能的,因为:

i.e., assigning to a temporary object, is possible because of:


(§3.10/ 5)为了修改对象,对象的左值是必要的,除了类类型的右值也可以用来修改它的指针情况。 [示例:为对象(9.3)调用的成员函数可以修改对象。 - end example]

(§3.10/5) An lvalue for an object is necessary in order to modify the object except that an rvalue of class type can also be used to modify its referent under certain circumstances. [ Example: a member function called for an object (9.3) can modify the object. — end example ]

所以这只是因为 A 类型,并且(隐式定义的)赋值运算符是成员函数。 (有关详情,请参见此相关问题 。)

So this works only because A is of class-type, and the (implicitly defined) assignment operator is a member function. (See this related question for further details.)

(因此,如果 rtByValue()返回,例如 int ,那么分配将不起作用。)

(So, if rtByValue() were to return, for example, an int, then the assignment wouldn't work.)

这篇关于C ++函数返回一个右值,但是可以分配一个新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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