0
const string &str1="test";

string &str2="test";

why str1 can compile but str2 can't? I can't understand it, Thanks,

jiafu
  • 6,338
  • 12
  • 49
  • 73

2 Answers2

11

There is a rule of the C++ language that states that you cannot bind a non-const lvalue reference (such as std::string&) to a temporary. The RHS of your expressions would have to yield a temporary std::string object, which can only be bound to a const std::string&.

You would see the same error with this simpler code, which does not involve any user defined types or converting constructors:

int i& = 42;

The rule itself makes sense: what would be the meaning of changing a temporary object? Instead of attempting to deal with this potentially confusing situation, the language forbids it outright. Of course, as with all rules, it is at some level an arbitrary and pragmatic decision, and I hear one widely used compiler has an "extension" that breaks this rule under certain circumstances.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1
std::string const& str = "test";

Normally, references cannot bind to temporaries; when the lifetime of the string expires you'd have a dangling reference right away. But since the reference is const, the life of the temporary is extented to that of the reference.

However, we can see the affect of this when we are returning by const reference:

std::string const& foo()
{
    return "Hello World";
}

int main()
{
    std::string str = foo(); // runtime error
}

Here the string is gone by the assignment, so the internal buffer of str is set to empty memory, probably causes a segmentation fault. A solution would be to simply return by value.

David G
  • 94,763
  • 41
  • 167
  • 253