Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c++ - 为什么我不必从std :: string的c_str函数中释放字符串?(Why I don’t have to free string from c_str function of std::string?)

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

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

How the function generate const char* and how it be destroyed?

(函数如何生成const char *以及如何销毁它?)

  ask by leejun translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(上面的说法是错误的,因为当namegetName返回而被破坏时,指针将变为无效。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...