I have a pretty large and verbose codebase and I am trying to find a trick to discover if an object of a particular class has gone through a delete
anywhere in the code, preferably by giving me a compilation error if this is the case.
I found out that you can overload the delete operator as in: void operator delete(void*)
and put this in the private section of the class of interest (so that whenever there is delete
on a pointer of that class it will fail compilation).
This could be the perfect solution, but alas it emits an error also when I use new
on that object. The compiler probably tries to generate the delete operator automatically once a new
is present. I don't want to alert on the new CLASS
appearances, just the delete
.
Any other ideas what I can do?
CodePudding user response:
You cannot new
an object for which the corresponding operator delete
is unusable because construction of the new object or the initializer of the new-expression may throw exceptions and then the new
expression must be able to call operator delete
to free the memory again.
Also note that often the global allocation and deallocation functions are used explicitly, so that your class-specific overload will be ignored. (Specifically with ::new
and ::delete
instead of new
and delete
.)
Furthermore, a lot of library functions (e.g. allocator-aware containers) do not use allocating new
/delete
expressions to construct dynamic storage duration objects, but instead allocate untyped memory first and then use placement-news and explicit destructor calls to construct and destroy objects. In this case also often the global allocation/deallocation functions are used explicitly.
You can't in general forbid specifically destruction of dynamic storage duration objects of a class type. A class should generally be agnostic to how its lifetime is managed. You can only e.g. delete the destructor, but then almost all uses of the class will be impossible.
You can of course also simply make an accessible overload of operator new
and operator delete
(as well as the array overloads operator new[]
and operator delete[]
) in the class and log calls to them at runtime by having them e.g. print a message. But as mentioned above this will still not catch a lot of cases, only uses of delete
(and delete[]
) exactly and it will also log cases of a new
expression calling operator delete
.