C++ temporary variable lifetime

后端 未结 3 958
清歌不尽
清歌不尽 2021-01-18 17:09

Is this code valid?

int foo()
{
    std::vector& v = std::vector(5, \"X\");

    // Do something silly...
         


        
3条回答
  •  我在风中等你
    2021-01-18 17:54

    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.

提交回复
热议问题