Let me share my Understanding on new operator. new operator do two jobs.
- Allocate memory
- construct memory at same place.
The new operator allocates memory using the global method::operator new(), and the memory is constructed at the same location using the placement new operator. The placement new is also in a global version.
If I overload the new operator in my class, the compiler will disable the use of global methods for memory allocation and construction for the same class. This means that I need to overload the new operator to allocate memory and the placement new operator to construct memory. In the following example, I am just overloading the new operator to allocate memory.
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << __FUNCTION__ << endl;
}
void* operator new(size_t _size)
{
cout << "Base new operator" << endl;
void *p = ::operator new(_size); // allocating dynamic memory using global new defination
if(p == NULL)
{
cout << "Sorry, Memory allocation failed";
return NULL;
}
return p;
}
};
int main()
{
Base *p = new Base();
return 0;
}
Output:
Base new operator
Base
Memory allocation is done with the overloaded new operator, and I'm not sure if memory is constructed using the global placement new operator; if so, who is calling the placement new operator, and if not, how is the same memory is constructed without the placement new operator?
To find out what happens if I overload the placement new operator. I tried the following example.
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << __FUNCTION__ << endl;
}
void* operator new(size_t _size)
{
cout << "Base new operator" << endl;
void *p = ::operator new(_size); // allocating dynamic memory using global new defination
if(p == NULL)
{
cout << "Sorry, Memory allocation failed";
return NULL;
}
return p;
}
void* operator new(size_t __size, void*p)
{
cout << "Base Placement new" << endl;
return p;
}
};
int main()
{
Base *p = new Base();
return 0;
}
output:
Base new operator
Base
Still placement operator is not called to construct the allocated same memory.
This may be a stupide question, but if someone can assist me in resolving my doubt, then your helpful advice will greatly improve my understanding.
The object is emplaced in the memory returned by your overloaded operator new. There is no way to override the emplacement itself, you can only override how it allocates the memory. If you want to have control over the placement aswell you will need to do something else than overriding the new operator (allocate memory and construct_at in another function for example).