In C++, "new operator" and "operator new" may seem similar, but they have significant differences in functionality.
new operator
"new operator" is a built-in operator in C++ used for allocating memory and invoking constructors to initialize objects. When using "new operator", it first allocates sufficient memory for the object (typically by calling the "operator new" function for memory allocation), then invokes the corresponding constructor on the allocated memory to construct the object.
Example:
cppclass MyClass { public: MyClass() { cout << "Constructor is called." << endl; } }; int main() { // Creating an instance of MyClass using new operator MyClass* myObject = new MyClass(); }
In this example, new MyClass() is a new operator, which invokes the default constructor of MyClass.
operator new
"operator new" is a function that can be overloaded, whose primary responsibility is to allocate sufficient memory space to hold objects of a specific type. It does not handle invoking constructors to initialize objects; instead, it merely provides the raw memory required for the object.
Example:
cppvoid* operator new(size_t size) { cout << "Custom operator new called." << endl; return malloc(size); // Allocate memory } class MyClass { public: MyClass() { cout << "Constructor is called." << endl; } }; int main() { // Directly calling operator new to allocate memory void* mem = operator new(sizeof(MyClass)); // Manually invoking the constructor on the allocated memory MyClass* myObject = new (mem) MyClass(); }
In this example, operator new(sizeof(MyClass)) only allocates memory and does not invoke the constructor of MyClass. The constructor is explicitly invoked later using placement new (new (mem) MyClass()).
Summary
In short, "new operator" is a higher-level operation that automatically handles both memory allocation and object construction. "operator new", on the other hand, is a low-level tool focused solely on memory allocation, typically used for custom memory management strategies or specific memory handling before constructing objects.