1

In the code below, why doesn't the assignment to get_string_val() give compilation error ? It looks like the function is returning an rvalue.

Of course, this is a simple example and this could be a member function returning a member variable. This can cause a bad bug if I had intended to return std::string& but mis-typed and returned std::string.

It looks like "xxx" is getting assigned to a temporary variable returned by get_string_val() ?

std::string get_string_val()
{
    std::string x;
    return x;
}

int main()
{

    get_string_val() = "xxx";
}
SergeyA
  • 61,605
  • 5
  • 78
  • 137
lichi101
  • 11
  • 3

1 Answers1

2

That is because std::string has an overloaded (custom) assignment operator. This operator can be invoked for rvalue std::string, as long as the object is not const-qualified.

You'd have a compilation error if your get_string would return const std::string.

By the way, things work differently for built-in types, which do not have operator= overloaded for them. int get_int(); get_int() = 25; would be a compilation error.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • I will like to add that this works even with default assignment operator (not just overloaded). Following compiles : `class A { public: int i; }; A get_A() { A a; return a; } main() { A d1; get_A() = d1; }` – lichi101 May 31 '18 at 18:12