本文介绍了引用未命名的临时对象(life time)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读之后,,我写了以下示例,它看起来像一个未命名的临时对象具有与其参考相同的生命时间!

After reading this answer from ildjarn, I wrote the following example, and it looks like an unnamed temporary object has the same life time as its reference!


  • 这是怎么可能的?

  • 是否在C ++标准中指定?

  • 哪个版本?

源代码: >

Source code:

#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


推荐答案

因为标准说,所以,因为它被认为是有用的。 rvalue引用和 const lvalue引用扩展临时表的生命周期:

Because the standard says so, because it's deemed useful. rvalue references and const lvalue references extend the lifetime of temporaries:


$ b $在 [C ++ 11:8.5.3 / 5] 中要求我们不将临时绑定到非 - const lvalue references。

and exhaustive wording in [C++11: 8.5.3/5] requires that we shall not bind temporaries to non-const lvalue references.

是的。所有人。

这篇关于引用未命名的临时对象(life time)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 08:04