返回字符串及其.c_str()的寿命
Lifetime of returned strings and their .c_str()
我遇到了此模式的多个实例(使用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 允许它作为扩展。
相关文章:
- 字符串变量,比如说"字符串str",可以直接复制到数组中吗?
- std::smatch str() 未返回正确的字符串
- 使用 str.erase() 的索引擦除字符串的元素?
- 在字符串中查找确切的子str
- 在 ss.clear() 之后使用 ss.str( " ") 用于新定义的字符串流
- .Net字符串是否可以在不复制的情况下交给fn(const char16_t*str)
- 从"char"到"const char*"的转换无效 [-fpermissive] str::atoi (字符串到整数)
- 字符串流.str().cstr()有问题吗
- 字符串中的 cin>>str+1 是什么C++?
- 我是否负责释放/删除stringstream.str()返回的字符串
- 流的内容和返回的字符串“str()”之间的差异
- 字符 *str;str= "HELLO" ;如何在不为字符串分配任何内存的情况下工作?
- 使用 str.at(x) 将字符串转换为 int
- 将字符串转换为无符号字符 str
- 在字符串 c++(无子字符串)上使用 str.find() 时执行操作
- 为什么当我们反转此函数中的字符串时,char *str 的指针没有改变?
- 使用 c.str 从字符串转换为 cstring
- 有没有使用 str.substr( ) 在给定位置提取子字符串的替代方法
- 使用str()和rdbuf()打印字符串流
- 转换str字符串以用于std::getline分隔符的字符串