AM Z
AM Z

Reputation: 431

What's the difference between delete[] and ::operator delete() in c++

I was watching a youtube series about data structures and how to made our-self data structure. But then the Instructor replaced the new[] with ::operator new() and delete[] with ::operator delete(), is there any difference? cuz this is the first time for me to see the ::operator thing in c++

Upvotes: 3

Views: 171

Answers (3)

molbdnilo
molbdnilo

Reputation: 66459

The new-expressions new T and new T[n] create objects in memory that they acquire.
The delete-expressions delete p and delete [] p destroy objects and release the memory where they were stored.

operator new is a memory allocation function, and operator delete is a memory deallocation function. They do not do anything more than manage memory, and correspond to C's malloc and free. They have those names in order to avoid introducing more keywords to the language – "operator new" and "operator delete" are just funky ways of spelling "allocate" and "deallocate".

The :: is the scope resolution operator and makes sure that these calls are specifically to the functions defined in the global scope.

The new-expressions and delete-expressions are not equivalent to these functions, but use them behind the scenes for memory management.

If you use operator new for allocating memory you must then also create an object in that memory, and if you release memory with operator delete you should first destroy the object that occupies the memory.

Upvotes: 1

Giogre
Giogre

Reputation: 1572

operator new works by allocating memory dynamically for a single object, while operator new[] instead creates an array object.

Placing :: before a command tells the compiler to employ the global namespace definition of that command, and not any possible overloaded version of it that might have been defined in your code.

Upvotes: 2

cigien
cigien

Reputation: 60430

In general, the :: operator is called the scope-resolution operator. The usage in this case is so that the correct version of a function can be selected. If you overload operator delete(), or operator new() for some class, and inside the implementation, you try to call delete on a member, the name lookup will only find the overloaded version. Using ::operator delete() resolves this by looking in the global namespace.

Here's an example from cppreference:

struct X {
    static void operator delete(void* ptr, std::size_t sz)
    {
        std::cout << "custom delete for size " << sz << '\n';
        ::operator delete(ptr);
    }
    static void operator delete[](void* ptr, std::size_t sz)
    {
        std::cout << "custom delete for size " << sz << '\n';
        ::operator delete(ptr);
    }
};

Upvotes: 3

Related Questions