Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator new inside namespace

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.

like image 723
iammilind Avatar asked Jun 02 '11 05:06

iammilind


People also ask

What is :: operator new?

The new operator invokes the function operator new . For arrays of any type, and for objects that aren't class , struct , or union types, a global function, ::operator new , is called to allocate storage. Class-type objects can define their own operator new static member function on a per-class basis.

What is the difference between operator new and the new operator?

new vs operator new in C++ When you create a new object, memory is allocated using operator new function and then the constructor is invoked to initialize the memory. Here, The new operator does both the allocation and the initialization, where as the operator new only does the allocation.

Can new operator be overloaded?

New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.

What is inside namespace std?

In C++, a namespace is a collection of related names or identifiers (functions, class, variables) which helps to separate these identifiers from similar identifiers in other namespaces or the global namespace. The identifiers of the C++ standard library are defined in a namespace called std .


1 Answers

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.

like image 93
sharptooth Avatar answered Sep 23 '22 10:09

sharptooth