1

i ran the code as shown and i am confused as to why a+b is a rvalue. From what i know, rvalue should only have a data or address and in such a case std::string should be a lvalue isn't it?

 void foo(const std::string&& input){ std::cout<<"RVALUE "<<input<<std::endl; } void foo(const std::string& input){ std::cout<<"LVALUE "<<input<<std::endl; } int main(){ std::string a = "Tom"; std::string b = "Cruise"; std::string c = a + b; foo(a+b); foo(c); } 

OUTPUT

 RVALUE TomCruise LVALUE TomCruise 
13
  • 1
    Brief intuition: Could you put a + b on the left hand side of an assignment statement? Would it make sense to say (a + b) = "anotherString";? No. The fully elaborated rules for what goes in which value category when are complex, but thinking about the left and right hand side of assignment statements is a good start. Commented May 14, 2021 at 3:25
  • 1
    a + b creates a temporary, which is then assigned to c or passed to foo(). That temporary is an rvalue Commented May 14, 2021 at 4:08
  • 1
    "From what i know, rvalue should only have a data or address" — That doesn't make any sense. What does it mean that an rvalue has something? Commented May 14, 2021 at 4:29
  • @NathanPierson Sure you can: godbolt.org/z/Knx34avEb. (You can call member functions on rvalues, and operator= is also a member function, though special.) Commented May 14, 2021 at 4:30
  • Well, huh, that's news to me. What is that actually doing? Commented May 14, 2021 at 4:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.