返回字符串及其 .c_str() 的生命周期

Phi*_*Lab 4 c++ string std stdstring

我遇到过这种模式的多个实例(boost::filesystem 仅用作示例):

boost::filesystem::path path = ...;
someFunctionTakingCStrings(path.string().c_str());
Run Code Online (Sandbox Code Playgroud)

在哪里

const std::string path::string() const
{
  std::string tmp = ...
  return tmp;
}
Run Code Online (Sandbox Code Playgroud)

虽然我从未遇到过这种模式的问题,但我想知道返回的字符串何时sting()被销毁,以及访问 的代码是否c_str()安全,因为c_str() 生命周期绑定到 std::string 生命周期

Bat*_*eba 5

someFunctionTakingCStrings(path.string().c_str());是安全的,因为标准保证匿名临时对象的生命周期path.string()在函数调用后仍然存在。因此,由 返回的指针c_str()是 的有效参数someFunctionTakingCStrings

const std::string path::string() const是安全的,因为从概念上讲,您正在返回 的值副本tmp,尽管实际上编译器会优化值副本(称为返回值优化的过程)。

类似于const std::string& path::string() const与您拥有的函数体相同的函数体将不会被定义(因为引用会悬空),并且

const char* ub_server()
{
    std::string s = "Hello";
    return s.c_str();
}
Run Code Online (Sandbox Code Playgroud)

也是未定义的,因为s在函数返回时已经超出范围。

最后,需要注意的是采取一个指向匿名临时作为函数调用的参数并不在标准C ++允许烦人虽然Visual C ++文件允许它作为一个扩展。