Home > Blockchain >  Reason for operator new returning void*;
Reason for operator new returning void*;

Time:01-19

What is the point/reason for operator new returning void*?

I've tried to come up with ideas as to why such an operator version exists, but I couldn't come up with one.

CodePudding user response:

operator new in C is a standard library function that is used to dynamically allocate memory for objects at runtime. The function is defined to return a pointer to void, which means it can return a pointer to any type of object. This allows the operator new to be used with any type, including user-defined types, without the need to overload the operator for each specific type.

Returning a void* pointer is also useful because it allows the programmer to type-cast the pointer to the appropriate type, thus allowing the same memory allocation function to be used for different data types. This is also useful when working with generic code, where the type of the object is not known until runtime.

Additionally, returning a void* pointer allows operator new to be used in conjunction with memory allocation libraries, such as those used in embedded systems, which may have different memory allocation requirements.

In short, the void* return type for operator new is done to allow for maximum flexibility and reusability of the function.

  • Related