雖然下面的代碼確實有效,但我不知道爲什麼。請解釋我。返回const char的函數*
#include <iostream>
using namespace std;
const char *f()
{
const char *p = "Hello!\n";
return p;
}
int main()
{
cout << f() << endl;
system("pause");
return 0;
}
從我瞭解到,在F中的7個字符()是在棧上分配(?),這意味着他們的記憶將盡快公佈爲f()結束,然而,指針爲f返回()仍指向應用程序內存中的有效地址(表示「Hello!」已成功發送到輸出)。爲什麼?
同樣的事情會爲
const int *f()
{
int i = 5;
const int *p = &i;
return p;
}
int main()
{
cout << *f() << endl;
system("pause");
return 0;
}
任何人都可以闡明這一些輕?
只有第二個片段調用UB,第一個就好了。 – 2014-11-24 13:42:52