返回字符串及其.c_str()的寿命

Lifetime of returned strings and their .c_str()

本文关键字:str 字符串 返回      更新时间:2023-10-16

我遇到了此模式的多个实例(使用boost ::文件系统仅用为示例):

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()Lifetime绑定到STD :: String Lifetime。

someFunctionTakingCStrings(path.string().c_str());是安全的,因为标准可以保证匿名临时path.string()的寿命能够幸存下来。因此,c_str()返回的指针是someFunctionTakingCStrings的有效参数。

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

类似于const std::string& path::string() const具有与您所拥有的功能相同的功能主体的东西,而不是不是(因为引用将 gangle )和

const char* ub_server()
{
    std::string s = "Hello";
    return s.c_str();
}

也未定义,因为s在函数返回时就超出了范围。

最后,请注意,将指针指向匿名临时性作为函数调用中的参数是不是标准C 中允许的,尽管令人讨厌的是,Visual C 允许它作为扩展。