從ildjarn閱讀this 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++書中相當公開。 – 2013-03-07 09:41:48
如果您只是嘗試在網頁上搜索您使用的短語,您應該可以找到答案:_臨時對象與其reference_具有相同的生存時間_ – 2013-03-07 09:48:16
[臨時生命期]的可能重複(http://stackoverflow.com/questions/4214153/lifetime-of-temporaries)/看看我發現了什麼 – 2013-03-07 09:54:45