tags:

views:

108

answers:

3

Hi everybody:

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.

+6  A: 

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.

Charles Bailey
+3  A: 

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.

Jerry Coffin
A: 

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?

AndreyT
One might naively guess that ADL applies to operator new, and hence that if you define operator new in namespace Test, then all classes in namespace Test will use it.
Steve Jessop