Question

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

Was it helpful?

Solution

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

OTHER TIPS

The normal lifetime of a temporary is until the end of the full expression in which it is created; it's not necessarily destructed immediately on use. If the temporary is used to initialize a reference, it's lifetime is extended to match that of the reference (with the notable exception of a temporary created in the initializer list of a constructor).

Of course, your code is illegal; if the reference is to a non-const, it can only be initialized with some sort of an lvalue. But if it were legal (and at least one compiler accepts it), the lifetime should be extended to match that of the reference.

You have a reference to a deallocated object. It works by 'sheer luck' (see The C++ Programming Language, section 10.4.10 Temporary Objects). You can't guarantee that it'll work in every compiler.

You can only be certain that the lifetime of the temporary is extended if it's bound to a const reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top