What are the limitations of overloading, overriding, and replacing new / delete?

I understand that there are 3 general ways to change the behavior of new ones and remove them in C ++:

  • The default replacement is new / delete and new [] / delete []
  • Overriding or overloading placement versions (overriding one of them with the memory address passed to it, overloading when creating versions that pass other types or numbers of arguments)
  • Overloading class-specific versions.

What are the limitations for making these new / delete behavior changes?

In particular, are there restrictions on signatures that can be used for new and deletion?

It makes sense if any version of the replacement must have the same signature (otherwise they would not be a replacement or would violate other code, for example, STL), but is it permissible that global allocation or class versions return smart pointers or some custom descriptors for example?

+4
source share
2 answers

First, do not confuse the new / delete expression with the operator new() function .

An expression is a language construct that performs construction and destruction. An operator is a regular function that performs memory allocation (de).

Only the default operator new(size_t) ( operator new(size_t) and operator delete(void *) can be used with the default expressions new and delete . All other forms are called β€œlayout” formats, and for those that you can only use new , but you need to destroy the objects manually by calling the destructor. Placement forms have a rather limited and specialized need. The most useful form of placement is global placement-new, ::new (addr) T , but this behavior cannot be changed (which, apparently, why is it the only popular ny).

The new operators must return void * . These distribution functions are much lower level than you would appreciate, so basically you "will know when you need to mess with them."

Repeat: C ++ shares the concepts of object construction and memory allocation. All you can do is provide alternative implementations for the latter.

+3
source

When you overload new ones and delete in the class, you effectively change the way you allocate and free memory for the class, asking it to provide you with this control.

This can be done when the class wants to use some kind of pool to distribute its instances, either for optimization or for tracking purposes.

Limitations, like almost any operator overloading, are a list of parameters that you can pass, and behavior that you are expected to adhere to.

0
source

Source: https://habr.com/ru/post/1389604/


All Articles