Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing return value of fundamental type and class type

Tags:

c++

There is such code:

#include <iostream>
#include <string>

int returnnumber() { return 2; }
std::string returntext() { return "siema"; }

int main() {

    std::cout << (returntext() += "cze") << std::endl; // siemacze
    //std::cout << (returnnumber() += 2) << std::endl; error: lvalue required as left operand of assignment

    return 0;
} 

Why is it possible to change return value of std::string, but not int?

like image 717
scdmb Avatar asked Oct 22 '11 17:10

scdmb


2 Answers

because std::string is a class type with a defined += operator as a member function.

and the standard allows you to call member functions on rvalues.

a silly consequence of that is that

struct S { int x; };
S foo() { return S(); }

int main()
{
    foo() = S();    // OK, uses member assignment operator.
    foo().x = 666;  // !Nah, can't assign to rvalue of built-in type.
}

compilation results:

Comeau C/C++ 4.3.10.1 (Oct  6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing.  All rights reserved.
MODE:strict errors C++ C++0x_extensions

"ComeauTest.c", line 7: error: expression must be a modifiable lvalue
      foo().x = 666;  // !Nah, can't assign to rvalue of built-in type.
      ^

1 error detected in the compilation of "ComeauTest.c".

however, compilers differ (or used to differ) about how strictly they applied this subtle rule, or if at all.

cheers & hth.,

like image 114
Cheers and hth. - Alf Avatar answered Nov 15 '22 04:11

Cheers and hth. - Alf


The left hand side of an assignment operator for a built-in type must be a modifiable lvalue but the return value of a function is always an rvalue if the function doesn't return a reference type.

operator+= is a member function of std::string and you can call a member function on an rvalue of class type.

like image 27
CB Bailey Avatar answered Nov 15 '22 03:11

CB Bailey