简体   繁体   English

警告:返回对本地临时对象的引用

[英]Warning: returning reference to local temporary object

Compiling the following: 编译以下内容:

namespace platform {
  struct event {};
  struct keyboard_event : public event {};

  const platform::event& wait_event()
  {
    return platform::keyboard_event(); 
  }
}

int main(int argc, const char* argv[])
{
  const platform::event& event = platform::wait_event();
  return 0;
}

Yields the following warning with clang 使用clang产生以下警告

main.cc:7:12: warning: returning reference to local temporary object [-Wreturn-stack-address]
    return platform::keyboard_event(); 
           ^~~~~~~~~~~~~~~~~~~~~~~~~~

Which makes sense but the new wording in C++11 seems to imply that returning a const reference to a value extends it's lifetime until the reference goes out of scope? 这有意义,但是C ++ 11中的新措辞似乎意味着将const引用返回到值会延长其寿命,直到引用超出范围为止?

The current draft isn't loading for me so I'll cite cppreference.com instead: 当前的草稿无法为我加载,因此我将引用cppreference.com:

The lifetime of a temporary object may be extended by binding to a const lvalue reference or to an rvalue reference (since C++11), see reference initialization for details. 可以通过绑定到const左值引用或右值引用(自C ++ 11起)来延长临时对象的生存期,有关详细信息,请参见引用初始化。

No, "returning a reference" does not magically extend any lifetime. 不,“返回参考”不会神奇地延长任何使用寿命。

The only time that lifetime is extended is when a prvalue (or an xvalue referring to a member of a prvalue) is bound to a reference variable , and the lifetime of the prvalue is extended to that of the variable: 延长生存期的唯一时间是将prvalue(或引用prvalue成员的xvalue)绑定到引用变量 ,并且prvalue的生存期扩展到变量的生存期:

struct Foo{};

{
    const auto & r = Foo{};   // Foo object not destroyed at semicolon...
    // ...
}
// ... but is destroyed only here.

Your prvalue is not bound to any variable, and hence no lifetime is extended. 您的prvalue未绑定任何变量,因此不会延长生存期。

(Also note that non-static class data members don't count as "variables" for this consideration, so you also can't extend lifetimes via constructor initializer lists if your class happens to have reference members.) (还要注意,出于这种考虑,非静态类数据成员不算作“变量”,因此,如果您的类恰好具有引用成员,那么您也无法通过构造函数初始化器列表来延长生命周期。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM