2
const string& s = "rajat";

works while

string& s = "rajat";

doesn't. Why?

prongs
  • 9,422
  • 21
  • 67
  • 105

2 Answers2

3

"rajat" is not a std::string, it is a null-terminated array of six char, i.e. char[6]

You can construct a std::string from a null-terminated array of char, and that's what happens when you write:

std::string s = "rajat";

When you want to initialize a string& you have to have a string for the reference to bind to, so the compiler tries to construct a string from the char array and bind the reference to that i.e.

std::string& s = std::string("rajat");

However this is illegal because the string that gets constructed is a temporary object and non-const references cannot bind to temporary objects, see How come a non-const reference cannot bind to a temporary object?

Community
  • 1
  • 1
Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
2

This will implicitly construct a temporary string from the string literal on the RHS. The temporary is then bound to a reference:

const string& s = "rajat";
//                 ^^^^^ temporary string is constructed from "rajat" literal

The language only allows const references to bind to temporaries, so this

string& s = "rajat";

is illegal, since it attempts to bind a non-const reference to a temporary string.

See this related GotW post, which also deals with lifetime issues.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480