operator new inside namespace

2019-01-19 16:24发布

问题:

namespace X
{
  void* operator new (size_t);
}

gives error message as:

error: ‘void* X::operator new(size_t)’ may not be declared within a namespace

Is it a gcc compiler bug ? In older gcc version it seems to be working. Any idea, why it's not allowed ?

Use case: I wanted to allow only custom operator new/delete for the classes and wanted to disallow global new/operator. Instead of linker error, it was easy to catch compiler error; so I coded:

namespace X {
  void* operator new (size_t);
}
using namespace X;

This worked for older version of gcc but not for the new one.

回答1:

@Sharptooth's Answer makes more sense if we consider this section from the standard:

3.7.3.1 Allocation functions [basic.stc.dynamic.allocation]

[..] 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. [..]

The above limitation is probably imposed for the very reason that @sharptooth's answer points out.



回答2:

This is not allowed because it makes no sense. For example you have the following

int* ptr = 0;

namespace X {
    void* operator new (size_t);
    void operator delete(void*);
    void f()
    {
       ptr = new int();
    }
}

void f()
{
    delete ptr;
    ptr = 0;
}

now how should the ptr be deleted - with global namespace operator delete() or with the one specific to namespace X? There's no possible way for C++ to deduce that.