cc
指向的数据的生命周期与其来自的字符串的生命周期相同(最好 - 如果修改字符串,它甚至更短)。
在你的情况下,foo()
的返回值是在cc
初始化结束时被破坏的临时值。
为了避免char *cc = foo().c_str()
编译错误,你不应该强制转换为char*
,您应该切换到const char *cc
,因为const char*
是什么c_str()
回报。但是,这仍然不能解决主要问题。
最简单的修复程序是:
printf("%s", foo().c_str()); // if you don't need the value again later
const string s = foo();
const char *cc = s.c_str(); // if you really want the pointer - since it's
// in the same scope as s, and s is const,
// the data lives as long as cc's in scope.
string s = foo();
printf("%s", s.c_str()); // if you don't store the pointer,
// you don't have to worry about it.
std::cout << foo(); // printf isn't bringing much to this party anyway.
+1提供正确的方法。 – 2011-05-10 08:22:09
完全正确; 'const引用'延长了一个右值的生命恰好是一个奇特的规则,'只''记住_value_也会。 (可能用C++ 11中的移动语义进行优化)。 – xtofl 2011-05-10 08:22:58
只要移动语义或RVO在工作中,使用值类型几乎是等价的。但是引用阻止我们依赖编译器优化。 – Xion 2011-05-10 08:26:52