Test::operator new
I tried to implement this:
namespace Test
{
void* operator new(size_t s)
{
return malloc(s);
}
}
But g++ (4.3.1) says:
void* Test::operator new(size_t)’ may not be declared within a namespace
Am I doing something wrong?
If yes, is there anyway to overload the operator new to be used in my classes? I do not want to create a base 开发者_如何转开发class and make all my classes inherit from such base class.
You can only (re-)define operator new
as a member of the global namespace or as (an implicitly static) member of a class.
If you don't have a common base class then you need to define operator new
for each class that you want a specialized implementation for. You could, of course, delegate to a common global function.
Yes, you're doing something wrong. According to the §3.7.3.1/1 of the standard, "An allocation function shall be a class member function or a global function; a program is ill-formed if an allocation function is declared in a namespace scope other than global scope or declared static in global scope."
That doesn't seem to allow what you want.
Well, the compiler has already told you exactly what you are doing wrong. Standalone 'operator new' may not be declared in any namespace other than global namespace.
Why on Earth did you decide to declare it in 'namespace Test'? What are you trying to achive by this?
精彩评论