[問題] pass by reference的問題
小弟對這邊觀念有點不清楚...希望請大家幫我解答一下
以下為程式碼(compiler是dev-c++ 4.9.9.2)
#include <iostream>
#include <string>
using namespace std;
string foo();
int main() {
string str = foo();
cout << "address: " << &str << endl << "content: " << str << endl;
str = foo();
cout << "address: " << &str << endl << "content: " << str << endl;
cout << "address: " << &foo()<< endl << "content: " << foo() << endl;
system("pause");
return 0;
}
string foo() {
string s;
s = "test";
cout << "In Foo! address: " << &s << endl << "In Foo! content: " << s << endl;
return s;
}
以下為執行的結果 我一行一行解釋並請各位看我觀念有何問題
In Foo! address: 0x22ff50
In Foo! content: test
address: 0x22ff50
content: test
以上四行的str和foo裡面的s記憶體位置一樣
因為創造str時即令他等於foo()
在這種狀況下 雖然沒有指定是return by reference
但compiler仍會自動以reference來傳回
In Foo! address: 0x22ff40
In Foo! content: test
address: 0x22ff50
content: test
這四行 因為重新指定str = foo() 所以系統就使用return by value
因此兩個字串變數的記憶體位置當然不一樣
In Foo! address: 0x22ff40
In Foo! content: test
In Foo! address: 0x22ff30
In Foo! content: test
address: 0x22ff30
content: test
這一塊我就搞不清楚了
一開始碰到&foo()時 先呼叫了一次foo 得到s的記憶體位置是0x22ff40 <--(*)
後來碰到foo() 再次呼叫一次 得到s的記憶體位置為0x22ff30
但最後在main()裡面 得到的&foo()值是0x22ff30
但我覺得奇怪的是 &foo()這個位置 不是應該是先被呼叫的foo()的記憶體位置嗎
那又由(*)的結果顯示 記憶體位置應該是0x22ff40 結果得到的卻是0x22ff30?
我總覺得是哪裡沒搞懂 想了半天想不出來 請大家幫我看看 感謝@@
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.45.229.243
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章