Hello. Two questions on operator new:
1. When do you need to include the <new> header? I am able to use and overload the normal new and placement new operators even if I don't include it.
2. The following trivial program doesn't compile.
Code:
#include <iostream>
using namespace std;
struct X
{
int i;
int j;
X(int a = 0, int b = 0): i(a), j(b){}
~X(){}
void* operator new(size_t, void* p)
{
cout << "an overloaded class X new operator" << endl;
return p;
}
};
void* operator new(size_t, void* p, char* s)
{
cout << s << ": ";
cout << "an overloaded global-scope new operator" << endl;
return p;
}
int main()
{
char* buffer = new char[sizeof(X)];
X* p = new(buffer, "test") X(99, 99);
p->~X();
delete[] buffer;
return 0;
}
However, if I remove the overloaded operator new in class X it works fine. Alternatively, I can leave the operator new in class X as it is and just add a :: to the 4th last line, i.e.
Code:
X* p = ::new(buffer, "test") X(99, 99);
Then it works fine two. The operator new in class X is obviously hiding the global operator new - even though it takes the wrong arguments for the call in question. Is that normal?