I have a code snippet like this
#include <cstring>
#define DISABLE_DEFAULT_NEW \
void* operator new(size_t aSize, void* aPtr); \
void operator delete(void* aPtr);
class A
{
public:
DISABLE_DEFAULT_NEW
A() {}
};
int
main()
{
A* a = new A();
return 0;
}
When I compile it, I see error messages like this
disable_new.cpp:17:10: error: no matching function for call to 'operator new'
A* a = new A();
^
disable_new.cpp:9:3: note: candidate function not viable: requires 2 arguments, but 1 was provided
DISABLE_DEFAULT_NEW
^
disable_new.cpp:3:9: note: expanded from macro 'DISABLE_DEFAULT_NEW'
void* operator new(size_t aSize, void* aPtr); \
^
1 error generated.
My question is where does the default new operator go? I'd expect the default syntax of new still work, is it behaviour mentioned anywhere in the spec?
They just hide the global ones. If provide operator new
at class scope,
(emphasis mine)
The new expression looks for appropriate allocation function's name firstly in the class scope, and after that in the global scope. Note, that as per name lookup rules, any allocation functions declared in class scope hides all global allocation functions for the new-expressions that attempt to allocate objects of this class.
That means, if you define any operator new
in the class, you have to define other necessary forms in the class too, e.g.
class A
{
public:
DISABLE_DEFAULT_NEW
A() {}
void* operator new ( std::size_t count ) { return ::operator new(count); } // forward to global operator new
};