My String class provides an operator char* overload to allow you to pass the string to C functions.
Unfortunately a colleague of mine just inadvertently discovered a bug.
He effectively had the following code.
StringT str;
// Some code.
delete str;
Is there anyway to prevent delete from casting the string object to a char* to prevent future bugs like this cropping up? std::string gets round this problem by not providing a char operator overload but, ideally, I’d like to keep the overload but prevent that delete from working.
Yes. Provide TWO implicit casts, by declaring (but not defining!)
operator char const volatile*. When you’re passing yourStringTto a C string function, overload resolution will still select your originaloperator char const*(exact match). Butdelete str;now becomes ambiguous.The declaration can be private, so if it would somehow be selected will be a compile-time error. The intended ambiguity occurs before overload resolution – the
privateonly serves to catch the exceedingly rare cases where thevolatileoverload would be selected somehow.