Default said:
werasm wrote:
If that library function stores off the pointer, or passes it around,
it may become invalid due to affects elsewhere in the code.
Yes, true. But then making a copy of the thing won't suffice - only a
literal or global would (perhaps a global const std::string or static -
in which case the const_cast would once again be required). Most of the
old API functions with parameters called "name" expected literals. The
only problem that you may have is that the function does not
necessarily complete synchronously. If the function has a result
indicating completion, such as strlen - or the above mentioned one, it
is safe to assume that the usage of the parameter has completed.
The fact remains, that for these unfortunate (const incorrect) APIs,
whether you create memory on the heap, or whether you const_cast c_str,
or whether you use a buffer on the stack (which is what I would prefer
over heap, BTW) - in all these cases you are likely to get failure.
Using literals or global/static consts then become your only option,
but what if your name is borne from your instance (dynamic), and is a
concatenation of various literals. Then we go back to:
1. Create copy on heap
- whack could delete it at worst void foo( char* name) { delete p;
/*fooled ya*/ }.
- whack could send it to another context (PostMessage...).
- whack could overindex...
- etc
2. Create copy on stack
- All the above still apply - obviously with undefined results.
3. Use a string.
- All the above still applies.
- In addition to this the string may not be modified - impossible for
local string BTW.
- If the string is modified by the function, then behaviour is
undefined - yes.
Alas...
For these unfortunate functions, I try to understand what the parameter
is used for, and then act accordingly. If it is used synchronously
only, and only performs reading (which I derive from the names of
parameters, return type and documentation etc), then I'm willing to go
for the const_cast. If not, well - then I'll be carefull of other
options mentioned too, as they are also error prone - especially in a
RoundRobin scheduling OS.
All said, if you're given a gun but you haven't seen one before, you
can shoot yourself! For this reason, to any newbies - I advise you
being very careful of such API's - using the most conservative
approach. const_cast is certainly less conservative.
Regards,
Werner