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.
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.
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.
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.
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 .
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 delete
d - with global namespace operator delete()
or with the one specific to namespace X
? There's no possible way for C++ to deduce that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With