Although I thought I understand the rvalue
and lvalue
semantics in C++, I seem to stomp over and over again into strange examples that prove to me that I don't know squat.
However there are two very simple and basic ones that I don't understand how they work. Before I compiled them I thought none would be ok, after I saw that (1)
works, I thought that (2)
would work too. However, (1)
works, (2)
doesn't:
(1) const std::string &s = "asd";
What happens here? My guess is that a temporary const string
object is constructed from "asd"
, and then s
is bound to that temporary object. But wouldn't then the temporary object be destroyed right after this line so we would be left with an invalid reference?
When I drop the const
qualifier:
(2) std::string &s = "asd";
I get a compiler error (VS 2013): cannot convert from 'const char [4]' to 'std::string &'
. Which seems to disprove my theory, because, according to it (my guess), a temporary string
object would be constructed from "asd"
and then s
assigned to it, which wouldn't generate any compile error.
So to sum up:
- To what is
s
bound? - What is the lifespan of the object that
s
is bound to? - What makes
(1)
compile and(2)
not (is it some conversion operators defined instd::string
or is it a C++ semantic)?