Operator New vs New Operator: A Deeper Dive
While often used interchangeably, "new operator" and "operator new" possess distinct roles in C memory management.
Operator New
Operator new is a function that allocates raw memory from the free store. It is low-level and conceptually similar to malloc(). However, it is typically used directly in custom containers or for specific scenarios. Operator new can be called explicitly as:
char *x = static_cast<char *>(operator new(100));
Additionally, operator new can be overloaded globally or for individual classes, with the signature:
void *operator new(size_t);
New Operator
The new operator, on the other hand, is typically used to create objects on the free store. Unlike operator new, it does not simply allocate memory; it allocates memory and invokes the class constructor. This creates a fully initialized object in memory, including any embedded objects or objects inherited from base classes.
my_class *x = new my_class(0);
Key Difference
The fundamental difference between operator new and the new operator is that operator new allocates raw memory, while the new operator not only allocates memory but also initializes the object at that location. The new operator relies on operator new for the memory allocation but handles the object initialization automatically.
The above is the detailed content of What's the Difference Between `operator new` and the `new` Operator in C ?. For more information, please follow other related articles on the PHP Chinese website!