operator new inside namespace

三世轮回 提交于 2019-11-27 06:52:55

问题


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.



来源:https://stackoverflow.com/questions/6210921/operator-new-inside-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!