Re: std::string reference initialized with string literal
On Mar 4, 4:11 am, "James Kanze" <james.ka...@gmail.com> wrote:
On Mar 3, 6:49 pm, "Mathias Gaunard" <loufo...@gmail.com> wrote:
This works because the constructor of std::string is implicit.
There is indeed a temporary being created.
I don't think that that was the problem the poster was asking
about. Normally, temporaries are destructed at the end of the
full expression in which they are created. If that happened
here, you'd end up with a dangling reference.
The original poster was not asking about a problem - but was asking
whether there was a problem with a declaration like:
const std::string& a = "Hello world";
The answer is that - by virtue of its "const" qualifier and the fact
that the lifetime of a temporary is extended to the match the lifetime
of a bound reference (with three execptions, none of which apply in
this case) - this initialization of the "a" reference is perfectly
valid and safe in C++.
In fact, the following declaration is equally fine (and for the same
const double& b = 2;
const std::string& e = c + d;
Note that all three of these declarations, including the orignal
mystring example, would be ill-formed without the "const" qualifier:
std::string& a = "test"; // Error
double& b = 2; // Error
Or course, the fact that references' initializers in the above
examples are still called "temporaries" does confuse matters. Since
the "temporary" objects created above turn out not to be very short-
lived at all - in fact they all persist for the entire life of the
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]