prongs
prongs

Reputation: 9606

initializing references in c++ doesn't work but initializing const references works, why?

const string& s = "rajat";

works while

string& s = "rajat";

doesn't. Why?

Upvotes: 2

Views: 114

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171383

"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?

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227468

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.

Upvotes: 2

Related Questions