Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I sensibly overload placement operator new?

Tags:

C++ allows overloading operator new - both global and per-class - usual operator new, operator new[] used with new[] statement and placement operator new separately.

The former two of those three are usually overloaded for using customized allocators and adding tracing. But placement operator new seems pretty straightforward - it actually does nothing inside. For example, in Visual C++ the default implementation just returns the address passed into the call:

//from new.h inline void* operator new( size_t, void* where ) {    return where; } 

What else could it do? Why and how could I sensibly overload placement operator new?

like image 936
sharptooth Avatar asked Sep 09 '10 08:09

sharptooth


People also ask

CAN NEW be overloaded?

New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.


2 Answers

The correct answer is you cannot replace operator placement new.

§18.4.​1.3 Placement forms
These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library.

The rationale: The only purpose of the allocation and deallocation operators is to allocate and deallocate memory, so when given memory nothing more should be done. (The standard specifically notes that these functions "Intentionally perform no other action.")

like image 137
GManNickG Avatar answered Sep 19 '22 06:09

GManNickG


Technically, a placement operator new is any operator new that takes additional arguments besides the size of the memory needed.

So, new(std::nothrow) X uses a placement operator new and so does new(__FILE__, __LINE__) X.

The only reason for overriding the operator new(size_t, void*) could be to add tracing information, but I think the need for that will be pretty low.

like image 31
Bart van Ingen Schenau Avatar answered Sep 19 '22 06:09

Bart van Ingen Schenau