I have a class with an implicit conversion operator to a pointer. Deallocating that pointer is not valid. Can I prevent the conversion to a pointer when used with the delete[] operator? I would like a compile time error. For the free function, I can delete an overload that takes the class as an argument.
void foobar(double*){}
struct A {
// Please pretend I have a good reason for doing this.
operator double*() const { return nullptr; }
};
void free(A&) = delete;
int main(){
A a;
// Just works TM
foobar(a);
// This compiles :(
delete[] a;
// This does not :)
//free(a);
return 0;
}
I think something clever would be needed for the desired effect.
A use case for implicit conversion: Say A implements a scoped array. Conversion makes A almost a drop in replacement for an alloc/dealloc pair. Templates and iterators requiring explicit conversion. Otherwise the call sites of c-like functions remain unchanged.
std::free(a)would compile even with your codeexplicitwould solve the problem.operator void*() const { return nullptr; }to make it an ambiguous situation.-Wdelete-incompleteexisting instead of just being an error.double* A::toDoublePtr() const { return ...; }