为什么我不必从 std::string 的函数中释放字符串c_str?
Why I don’t have to free string from c_str function of std::string?
为什么我不必从 std::string 的函数中释放字符串c_str? 函数如何生成常量字符*以及如何销毁它?
从c_str()
返回的const char*
由std::string
本身管理,并在std::string
过期时销毁。在这方面,必须注意他们不要在std::string
被销毁后尝试使用从c_str()
返回的指针:
const char* getName()
{
std::string name = "Joe";
return name.c_str();
}
以上是错误的,因为当name
在getName
返回时被破坏时,指针将变为无效。