1

I am in need to write / overload / override default C++ new operator. I found this below information -

non-allocating placement allocation functions
void* operator new  ( std::size_t count, void* ptr );
(9) 
void* operator new[]( std::size_t count, void* ptr );
(10)    

As per documentation it state -

Called by the standard single-object placement new expression. The standard library implementation performs no action and returns ptr unmodified.

I am not able to clear myself by what is meant by "non-allocating placement allocation functions"?

Programmer
  • 8,303
  • 23
  • 78
  • 162

3 Answers3

4

These overloads are used by placement new. This is an expression that creates an object at a memory location, but doesn't allocate space for it. For instance, in this toy example:

void foo() {
    void *raw = malloc(sizeof(int));
    int *pint = new(raw) int(10);

    pint->~int();
    free(raw);
}

This illustrates that if we need to create an object in memory allocated by something that is not the C++ standard library (in this case, the C allocation functions), special syntax is used to create an object at that location.

The placement operator new accepts the address, and returns it unchanged. Thus the new expression just creates an object there. Naturally, we cannot call delete to free said object and memory, we must do an explicit destructor call, followed by the correct memory deallocation function.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Note: the pseudo-destructor call is not necessary for built-in types, or class types with trivial destructors – M.M Feb 28 '18 at 22:51
2

Non-allocating placement allocation function is a form of new that doesn't allocate memory, but rather constructs an object in pre-allocated memory.

See this answer for more details.

Dev Null
  • 4,731
  • 1
  • 30
  • 46
1

To answer the question implied in your title:

It is not permitted to supply your own replacement function for the non-allocating forms of operator new. This is covered in the standard (N4659):

Non-allocating forms [new.delete.placement]

These functions are reserved; a C++ program may not define functions that displace the versions in the C++ standard library.

You can only replace the forms of operator new which are listed as Replacable under the section of the Standard labelled [new.delete].

M.M
  • 138,810
  • 21
  • 208
  • 365
  • 1
    cppreference contains various class-specific replacement functions for placement new (and placement delete) [here](https://en.cppreference.com/w/cpp/memory/new/operator_new) under "Class-Specific allocation functions". Maybe you meant global placement new's only can't be replaced? – KeyC0de Nov 05 '18 at 10:23