When using some library functions (e.g. strftime()
, strcpy()
, MultiByteToWideChar()
) that deal with character arrays (instead of std::string
's) one has 2 options:
- use a fixed size array (e.g.
char buffer[256];
) which is obviously bad because of the string length limit use
new
to allocate required size which is also bad when one wants to create a utility function like this:char * fun(void) { char * array = new char[exact_required_size]; some_function(array); return array; }
because the user of such function has to
delete
thearray
.
And the 2nd option isn't even always possible if one can't know the exact array size/length before using the problematic function (when one can't predict how long a string the function will return).
The perfect way would be to use std::string
since it has variable length and its destructor takes care of deallocating memory but many library functions just don't support std::string
(whether they should is another question).
Ok, so what's the problem? Well - how should I use these functions? Use a fixed size array or use new
and make the user of my function worry about deallocating memory? Or maybe there actually is a smooth solution I didn't think of?