operator new inside namespace

后端 未结 2 1541
栀梦
栀梦 2020-12-11 05:19
namespace X
{
  void* operator new (size_t);
}

gives error message as:

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


        
相关标签:
2条回答
  • 2020-12-11 05:42

    @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.

    0 讨论(0)
  • 2020-12-11 05:51

    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.

    0 讨论(0)
提交回复
热议问题