C++ temporary variable lifetime

后端 未结 3 921
清歌不尽
清歌不尽 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.

    0 讨论(0)
  • 2021-01-18 18:04

    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.

    0 讨论(0)
  • 2021-01-18 18:13

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

    0 讨论(0)
提交回复
热议问题