【发布时间】:2013-03-17 18:16:08
【问题描述】:
在 VS2010 中运行此代码,我收到如下所示的警告,但控制台上会输出 C 字符串“f()”和“g()”。
问题 1:为什么 f() 会生成警告而 g() 不会?在程序结束之前,字符串文字不是一直保存在静态内存中吗?
问题 2:当我在 main() 中注释掉对 h() 的调用时,代码会崩溃。为什么会有不同的行为?
#include<iostream>
const char* const& f()
{
return "f()"; // warning C4172: returning address of local variable or temporary
}
const char* g()
{
return "g()"; // no warning
}
const std::string& h()
{
return "h()"; // warning C4172:
}
int main()
{
std::cout << f() << '\n';
std::cout << g() << '\n';
// std::cout << h().c_str() << '\n'; // comment out and program crashes
}
【问题讨论】:
标签: c++ string compiler-warnings c-strings