Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "::delete" in C++?

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?

like image 505
Bryan Muscedere Avatar asked Aug 20 '18 15:08

Bryan Muscedere


2 Answers

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

like image 183
Basile Starynkevitch Avatar answered Nov 11 '22 08:11

Basile Starynkevitch


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.

like image 22
dfrib Avatar answered Nov 11 '22 06:11

dfrib