Re: std::string reference initialized with string literal
On Mar 3, 6:49 pm, "Mathias Gaunard" <loufo...@gmail.com> wrote:
On Mar 3, 5:07 am, "Ivan Novick" <ivan.d.nov...@gmail.com> wrote:
const std::string& mystring = "Hello World";
This code works on my box, but it seems wrong. Can we initialize a
reference with a string literal? I am assuming a temporary is created
in the process, but I am not seeing how this can work.
The code is absolutely correct, and the fact that this is allowed is
actually very important.
For example you can call a function which takes a const std::string&
as an argument with a string literal.
But that's not important here; the temporary will be destructed
at the end of the full expression in which you call the
function. By that time, you'll have returned from the function,
and everything will be hunky dory (unless the function has taken
the address of the temporary, and is keeping a pointer to it for
later use, of course).
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.
James Kanze (Gabi Software) email: firstname.lastname@example.org
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]