2017-02-06 30 views
0
#include <iostream> 
#include <string> 

using namespace std; 


string& funRef (string& s) { 
string t = s; 


return t; 
} 

int main() { 
string s1 = "I'm a string!"; 
string& s2 = funRef(s1); 
s2 = "YOUR STRING IS MINE"; 

cout << s1 << endl; 
cout << s2 << endl; 
} 

參考爲什麼它打印出來:關於C++

我是一個字符串!

\ 367 \ 277_ \ 377 \ 367 \ 277_ \ 377M

我想S2被分配以 「您的字符串是我的」。

s2發生了什麼?

+0

它引用了一個被銷燬的對象,'string t = s;''t'在'funref'不在範圍內時被銷燬。 – George

回答

0

大部分代碼都是不相關的。

這歸結爲簡單的未定義行爲,因爲在這裏你是返回一個引用局部變量:

string& funRef(string& s) 
{ 
    string t = s; 
    return t; 
} 

字符串t儘快死去的呼叫funRef結束,但你試圖在稍後使用對t的引用。

你不能那樣做。