is actually a "new expressions" that calls the "operator new" and converts the void* to the destination type* (int* in this case).
Does the "new expression" also need to be overloaded when overloading the "operator new"?
2) Lets say I've overloaded operator new to take an extra argument :
1 2 3 4 5
struct elem
{
int a;
void* operatornew (size_t nbytes, int initA);
};
and now I cant use the ordinary "new expression".
elem *a = new elem;
Would exposing the default "operator new" solve the problem ? Is there any way to expose it without writing an extra member function that simply calls ::operator new(nBytes) ?
3) Do I have to call the class/struct constructor in the overloaded operator new explicitly (probably by using placement new after malloc) or does it get called implicitly ?
Does the "new expression" also need to be overloaded when overloading the "operator new"?
You cannot change new-expression at all.
and now I cant use the ordinary "new expression".
Your operatornew requires additional parameter you didn't provide. So either add another operatornew with default signature or provide that parameter explicitely:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <new>
struct elem {
int a;
void* operatornew (size_t nbytes, int initA)
{
std::cout << initA << '\n';
return ::operatornew(nbytes);
}
};
int main()
{
elem* x = new(4) elem;
}
4
Do I have to call the class/struct constructor in the overloaded operator new explicitly (probably by using placement new after malloc) or does it get called implicitly ?
new-expression does two things:
1) Allocate memory (using either global or member operatornew)
2) Create object in allocated memory (same as placement new)
Technically, no: it does not call placement new, it is just an action new-expression does, but your code will behave same way as standard implementation does.
Things we call placement new are just version of operator new which are called when new-expression is given additional arguments. Standard version provides non-overloadable void* operatornew ( std::size_t count, void* ptr ); and array equivalent which just returns second parameter: no actual cllocation done. You are free to implement another versions of placement-new (or new-with-params)