How does std::string::c_str() return a c-string th

2019-06-20 09: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().