I know the process of returning a char array is simple, but returning an array without any memory leaks is a solution that seems to elude me.
I'm creating a custom string class, and I would like to be able to return a copy of the string without having to worry about memory leaks. Would it be possible to return a copy of the string without having to allocate new memory off the heap, copy the string and then return that?
I saw that the string class's c_str declaration returns an array of type const. Would this be the solution?
As a side note, I've also seen code similar to this quite often: const charT* c_str ( ) const;
What is the purpose of the second const?
Short of writing your own string class, or using an existing one, there's no solution that will work under all circumstances other than returning a dynamically-allocated array and having the caller take care of deallocation.
A possibility is to have a global char array and return that, but it's not recommendable.
What is the purpose of the second const?
It allows member functions to be called using const this parameters. For example:
const std::string s;
s.c_str(); //<- without the const in the declaration, this call would be invalid
I see what you mean. Sorry, I was thinking about something else, but my argument was still the same.
I guess that would make sense. If the variable is going out of scope, there wouldn't be much use for the internals. The moral of the story: Return the whole object. Alright, thanks.