I'm currently looking at C++ code that uses ::delete
to delete a pointer.
A meaningless example of this is:
void DoWork(ExampleClass* ptr)
{
::delete ptr;
}
What is the purpose of using the delete keyword in this way?
In some cases, the operator delete
might be redefined -actually overloaded- (for example, your Class
might define it and also define operator new
). By coding ::delete
you say that you are using the standard, "predefined", deletion operator.
A typical use case for redefining both operator new
and operator delete
in some Class
: you want to keep a hidden global set of all pointers created by your Class::operator new
and deleted by your Class::operator delete
. But the implementation of your delete
will remove that pointer from the global set before calling the global ::delete
This is using the delete
expression, but with the optional ::
prefix.
Syntax
::
(optional)delete
expression (1)...
Destroys object(s) previously allocated by the
new
expression and releases obtained memory area.
Using the ::
prefix will affect lookup:
The deallocation function's name is looked up in the scope of the dynamic type of the object pointed to by expression, which means class-specific deallocation functions, if present, are found before the global ones.
If
::
is present in the delete expression, only the global namespace is examined by this lookup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With