Why is this object considered an rvalue?

Why is the object that I pass to the constructor ClassAconsidered rvalue (temporary)? I know that setting a parameter constwill result in an error, but I want to understand what is going on.

Does this behavior work fine for calling a function, but not for a constructor?

#include <iostream>

using namespace std;

class ClassA {
public:
   ClassA() {}
   ClassA(ClassA&) {}
};

void f(ClassA&) {}

int main() {
   ClassA a;

   // Invalid initialization of non-const reference of type 'ClassA&' from an
   // rvalue of type 'ClassA'
   ClassA b = ClassA(a); 

   // Works fine
   f(a);

   return 0;
}
+4
source share
1 answer

The value of r here is an expression ClassA(a).

ClassA b = ClassA(a);

This is a copy initialization, so it will try to call the copy constructor ClassAwith a result ClassA(a)that is an rvalue. You announced that the copy constructor accepts ClassA&, which cannot communicate with rvalues, so you get an error.

, , const , r, :

ClassA b (a);
ClassA b {a}; //C++11
ClassA b = a;

, ClassA b = ClassA(a); -, , , elided. , - .

+10

Source: https://habr.com/ru/post/1626157/


All Articles