为什么我不必从 std::string 的函数中释放字符串c_str?

Why I don’t have to free string from c_str function of std::string?

本文关键字:字符串 释放 str 不必 std 为什么 string 函数      更新时间:2023-10-16

为什么我不必从 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();
}

以上是错误的,因为当namegetName返回时被破坏时,指针将变为无效。