Re: Global Operators New/Delete and Visibility Across Translation Units
dila ha scritto:
Hello,
I have overloaded the global new, delete, new[] and delete[] operators
inside a "static library". The library uses private memory allocation
routines that must not be accessible from other translation units.
Other translation units are therefore expected to define and use their
own new/delete operators.
When I link to this library the global new/delete operators conflict,
and although no linker warnings are generated, the result is that
translation units access each others memory allocation routines.
That's the main reason why your approach is not a good idea.
How can I limit the scope of these operator definitions? Apparently it
is not enought to declare them as 'inline' functions, which should only
make them available to translation units which explicitly include the
headers where they are defined.
Declaring them inline is no good. In fact you would violate ODR making
the program ill-formed.
The usual way to limit the scope of operators new/delete is to declare
them as member functions, instead of in global namespace. For example:
class MyClass
{
// stuff
void* operator new(size_t n);
void operator delete(void* p);
// possibly new[] and delete[] also
};
If you have several classes that uses the same memory manager, you can
factor the allocation/deallocation functions in a common base.
Notice that this method don't work if you allocate built-in types with new.
To avoid this ambiguity I have considered overloading one set of
operators with redundent parameters, such as: void* operator new(
size_t, int )
That's another solution, but more error prone, IMHO, because you might
forget to use the overloaded operator new. If you choose to follow this
path, be careful to properly handle the operator delete (see
http://www.research.att.com/~bs/bs_faq2.html#placement-delete for details).
Other solutions are possible, according to your specific use cases. They
mainly involve either allocators or the factory pattern.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]