How does std::string::c_str() return a c-string that does not cause a memory leak or undefined c-string contents?

蓝咒 提交于 2019-12-10 13:34:49

问题


I'm writing a string class that is similar to std::string for a homework assignment, but I cannot figure out how to return a c-string that does not cause a memory leak and is guaranteed to stay the same until it is no longer in use. I currently have:

const char* string::c_str()
{
    char c[_size+1];
    strncpy(c,_data,_size);
    c[_size]='\0';
    return c;
}

but the contents are overridden shortly after it is called. If I do dynamic allocation, I'll have either a memory leak or only one c-string can exist from a given string at any time. How can I avoid this?


回答1:


But the string pointed to by c_str is only well-defined until the std::string is next modified (or destroyed).

One way to achieve this might be simply to return a pointer to your internal buffer (assuming it's null-terminated). Bear in mind that a standards-compliant c_str has to operate in O(1) time; so copying is not permitted.




回答2:


From http://www.cplusplus.com/reference/string/string/c_str/:

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only guaranteed to remain unchanged until the next call to a non-constant member function of the string object.




回答3:


The buffer returned by c_str() isn't guaranteed to stay the same or even valid until it's no longer used.

It's only guaranteed to stay valid until the std::string is changed in any way.

The implementation is straight-forward: just keep the internal representation of the string null-terminated at all times, and return a pointer to the internal representation from c_str().



来源:https://stackoverflow.com/questions/11336351/how-does-stdstringc-str-return-a-c-string-that-does-not-cause-a-memory-lea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!