Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ temporary variable lifetime

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 :)

like image 661
Yippie-Ki-Yay Avatar asked May 10 '12 18:05

Yippie-Ki-Yay


1 Answers

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).

like image 82
ildjarn Avatar answered Sep 28 '22 01:09

ildjarn