Home >Backend Development >C++ >What's the Difference Between the C `new` Operator and `operator new`?
Differentiating between the "new operator" and "operator new" can be confusing. Here's an in-depth explanation to clarify the distinction.
Operator new is a standard C function that allocates uninitialized memory from the heap. It operates similarly to the malloc() function but is specific to C .
You can invoke operator new directly to reserve raw memory:
char *x = static_cast<char *>(operator new(100));
Overloading operator new is possible, allowing you to customize memory allocation for specific classes or globally.
The "new operator" is the primary method used to create objects in C . It combines the functionalities of operator new and class constructors.
When you use the new operator:
my_class *x = new my_class(0);
It first calls operator new to allocate raw memory for the object my_class. Subsequently, it invokes the constructor my_class(0) to initialize the object within that memory. If the my_class contains embedded or base class objects, their constructors are also called.
The fundamental difference between the "new operator" and "operator new" lies in their behavior:
In summary, operator new is a lower-level function for allocating raw memory, while the "new operator" is a higher-level abstraction that seamlessly handles memory allocation and object initialization.
The above is the detailed content of What's the Difference Between the C `new` Operator and `operator new`?. For more information, please follow other related articles on the PHP Chinese website!