C++ temporary variable lifetime

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

提交回复
热议问题