The const char*
return from c_str()
is managed by the std::string
itself, and is destroyed when the std::string
goes out of date.
(从c_str()
返回的const char*
由std::string
本身管理,并在std::string
过时时销毁。)
In this regard, one must be careful they don't attempt to use the pointer returned from c_str()
after the std::string
is destroyed: (在这方面,必须小心,不要在销毁std::string
之后尝试使用从c_str()
返回的指针:)
const char* getName()
{
std::string name = "Joe";
return name.c_str();
}
The above is wrong, because when name
is destructed as getName
returns, the pointer will become invalid.
(上面的说法是错误的,因为当name
随getName
返回而被破坏时,指针将变为无效。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…