返回字符串及其 .c_str() 的生命周期 [英] Lifetime of returned strings and their .c_str()
问题描述
我遇到过这种模式的多个实例(boost::filesystem 仅用作示例):
I've come across multiple instance of this pattern (with boost::filesystem only used as example):
boost::filesystem::path path = ...;
someFunctionTakingCStrings(path.string().c_str());
哪里
const std::string path::string() const
{
std::string tmp = ...
return tmp;
}
虽然我从来没有遇到过这种模式的问题,但我想知道sting()
返回的字符串什么时候被销毁,访问c_str()
的代码是否是安全,因为 c_str() 生命周期绑定到 std::string 生命周期.>
Although I have never experienced problem with this pattern, I was wondering when the string returned by sting()
is destroyed and whether the code accessing the c_str()
is safe as the c_str() lifetime is bound to std::string lifetime.
推荐答案
someFunctionTakingCStrings(path.string().c_str());
是安全的,因为标准保证匿名临时的生命周期path.string()
在函数调用中存活下来.所以c_str()
返回的指针是someFunctionTakingCStrings
的有效参数.
someFunctionTakingCStrings(path.string().c_str());
is safe since the standard guarantees that the lifetime of the anonymous temporary path.string()
survives the function call. So the pointer returned by c_str()
is a valid parameter for someFunctionTakingCStrings
.
const std::string path::string() const
是安全的,因为从概念上讲,您返回的是 tmp
的值副本,尽管实际上编译器会优化值副本(称为命名返回值优化的过程).
const std::string path::string() const
is safe since, conceptually, you are returning a value copy of tmp
, although in practice a compiler will optimise out the value copy (a process called named return value optimisation).
类似于 const std::string&path::string() const
与您拥有的函数体相同的函数体将不会被定义(因为引用会悬垂),并且>
Something like const std::string& path::string() const
with the same function body as the one you have would not be defined (since the reference would dangle), and
const char* ub_server()
{
std::string s = "Hello";
return s.c_str();
}
也是未定义的,因为 s
在函数返回时超出范围.
is also undefined, as s
is out of scope by the time the function returns.
最后,请注意,在标准 C++ 中不允许允许将指向匿名临时对象的指针作为函数调用中的参数,尽管令人讨厌的是,Visual C++ 允许将其作为扩展.
Finally, note that taking a pointer to an anonymous temporary as a parameter in a function call is not allowed in standard C++ although annoyingly, Visual C++ allows it as an extension.
这篇关于返回字符串及其 .c_str() 的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!