【问题标题】:Reference to an unnamed temporary object (life time)引用未命名的临时对象(生命周期)
【发布时间】:2013-03-07 09:39:25
【问题描述】:

ildjarnthis answer后,我写了下面的例子,看起来一个未命名的临时对象和它的引用有相同的生命周期!

  • 这怎么可能?
  • 是否在 C++ 标准中指定?
  • 哪个版本?

源代码:

#include <iostream>  //cout
#include <sstream>   //ostringstream 

int main ()
{
        std::ostringstream oss;
        oss << 1234;

        std::string const& str = oss.str();
        char        const* ptr = str.c_str();

        // Change the stream content
        oss << "_more_stuff_";
        oss.str(""); //reset
        oss << "Beginning";
        std::cout << oss.str() <<'\n';

        // Fill the call stack
        // ... create many local variables, call functions...

        // Change again the stream content
        oss << "Again";
        oss.str(""); //reset
        oss << "Next should be '1234': ";
        std::cout << oss.str() <<'\n';

        // Check if the ptr is still unchanged
        std::cout << ptr << std::endl;
}

执行:

> g++ --version
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-54)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
> g++ main.cpp -O3
> ./a.out
Beginning
Next should be '1234':
1234

【问题讨论】:

  • const 引用延长了临时对象的生命周期这一事实应该在您的 C++ 书籍中得到充分说明。
  • 如果您尝试在网上搜索您使用的短语,您应该会找到答案:temporary object has the same life time as its reference
  • Lifetime of temporaries 的可能副本 / 看看我发现了什么
  • @olibre:是的,你是对的。我一定是喝醉了。
  • @olibre: You cannot.

标签: c++ reference temporary object-lifetime


【解决方案1】:

这怎么可能?

因为标准是这样说的,因为它被认为是有用的。右值引用和const 左值引用延长了临时对象的生命周期:

[C++11: 12.2/5]: [..] 引用绑定的临时对象或引用绑定的子对象的完整对象的临时对象仍然存在 在引用的生命周期内,除了 [..]

[C++11: 8.5.3/5] 中详尽的措辞要求我们不得将临时对象绑定到非const 左值引用。


它是否在 C++ 标准中指定? 哪个版本?

是的。全部。

【讨论】:

    【解决方案2】:

    临时绑定到 const 引用会增加临时对象的生命周期,直到常量引用的生命周期。

    好读:

    GotW #88: A Candidate For the “Most Important const”


    是的,从引入引用开始就在 C++ 标准中指定了它。
    因此,如果您想知道这是否是 C++11 功能,不,不是。它已经存在于 C++03 中。

    【讨论】:

      【解决方案3】:

      Lightness Races in Orbit 是对的。而且我认为这个例子会更简洁。

      #include <iostream>  //cout
      #include <string>
      
      int main ()
      {
          using namespace std;
          int a = 123;
          int b = 123;
      //  int       & a_b = a + b; // error!
          int const & a_b = a + b;
          cout<<"hello world!"<<endl;
          cout<<a_b<<endl;
      }
      

      【讨论】:

        猜你喜欢
        • 2023-02-07
        • 2012-11-15
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        • 2013-11-20
        • 2019-01-06
        • 1970-01-01
        相关资源
        最近更新 更多