我遇到过这种模式的多个实例(仅使用 boost::filesystem 作为示例):
boost::filesystem::path path = ...;
someFunctionTakingCStrings(path.string().c_str());
where
const std::string path::string() const
{
std::string tmp = ...
return tmp;
}
虽然我从未遇到过这种模式的问题,但我想知道何时返回字符串sting()
是否被破坏以及访问的代码是否c_str()
是安全的c_str() 生命周期绑定到 std::string 生命周期 https://stackoverflow.com/questions/6456359/what-is-stdstringc-str-lifetime.
someFunctionTakingCStrings(path.string().c_str());
是安全的,因为该标准保证匿名临时的生命周期path.string()
函数调用后仍然存在。所以返回的指针c_str()
是一个有效参数someFunctionTakingCStrings
.
const std::string path::string() const
是安全的,因为从概念上讲,您返回的是一个值副本tmp
,尽管实际上编译器会优化值副本(一个称为命名返回值优化).
就像是const std::string& path::string() const
与您拥有的功能体相同not被定义(因为参考将dangle), and
const char* ub_server()
{
std::string s = "Hello";
return s.c_str();
}
也是未定义的,因为s
当函数返回时超出范围。
最后,请注意,在函数调用中将指向匿名临时对象的指针作为参数是not标准 C++ 中允许,尽管令人恼火的是,Visual C++ 允许将其作为扩展。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)