Luke Bourne Luke Bourne - 2 months ago 6
C++ Question

Accessing the number passed into new[] c++

I am implementing a custom memory allocation process and am globally overriding new, new[] and delete, delete[].
The memory allocation takes the size of the object and an optional 'nObjects' parameter where its the amount of objects to be created (defaults to 1).

new works fine, but with new[] the size_t value just returns the total value of nObjects*sizeOfObject. So i have no way of knowing the number of objects that are actually being allocated, just the size.

I looked in the assembly and the number of objects is definitely there, being passed around, but my question is: Is there a safe way to access it within the scope of the global new[] override?

Thanks.

EDIT:

Btw, I'm creating the custom allocation so that any other class that is created with it does not need to do anything extra to account for memory allocation. eg. I can just create class whatever{} and allocate it, I don't need to derive it from anything or put anything extra in its constructor/destructor.

The reason i'm doing this is too account for some external uses of new that i have no control over other than in the global new override.

Answer

Is there a safe way to access it within the scope of the global new[] override?

No such way.

new operators are just memory allocations functions, they only get the number of bytes they need to allocate (just like malloc).

This is new expression that accepts the number of objects, calls operator new (which you can overload) and then invokes the constructor. new expression cannot be overloaded.