Is this code valid?
int foo()
{
std::vector<std::string>& v = std::vector<std::string>(5, "X");
// Do something silly...
return 42;
}
For some reason I thought that the temporary std::vector
object (right from the assignment sign) should be destructed right after it's construction (thus rendering the reference invalid).
However, debugging proves that I'm wrong and, well, I realized that I don't quite understand why does the temporary variable is destructed when the function returns.
I guess I have a strong misunderstanding of something fundamental, so please enlighten me :)
The code you've shown is illegal – temporaries can only bind to rvalue references or const lvalue references.
VC++ happens to allow it as an extension (and gives a level 4 warning saying so).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With