-
Returning char *
This is about the string class function that returns a char * (null-terminated).
char *MYSTRING::c_str();
I thought it would be easy but I am having a few roadblocks:
1) If I declare a local array and set it up correctly, I can't return a reference or a pointer to it. Also, since the size is variable, I can't create an array in the first place.
2) Only thing left is dynamic memory allocation. However, that leads to a memory leak.
So... how else can I return a null-terminated c string? The guts of my class use a char array but it isn't null-terminated so I can't return that...
-
You should be returning a const char*, not a char*.
I would null terminate your char array inside the class. You could also just always allocate space for at least one extra character, and then only add the null to the end only when they call c_str().
-
That would an easy way to do it. Unfortunately I'd have to go back and change my class invariant and probably a bunch of other things too.
That is good advice though, I really don't think there is any other more straightforward way to do it...
BTW, anyone know how std::string does it?
-
>> BTW, anyone know how std::string does it?
That's where I got the ideas. The libraries I've looked at either always append the null or just leave space for it and append it when necessary.
You shouldn't have to change that much if you only set the null when c_str() is called. You have to write c_str() obviously, but you only have to change your allocation functions to always just add one to the final allocation value.
-
std::string can do it whatever way it likes, but I haven't heard of any implementation that doesn't do it Daved's way.
Another option would be to have another pointer member in the string class for the c_str() return value, which you delete[] at the next modification. This is valid behaviour for a basic_string-like class because the return value of c_str() is only guaranteed to be valid until the next modification. However, it requires you to think about what operations count as modifications. Which is a useful exercise in itself, but perhaps not what you want to do right now.