overloaded new/delete with stl/templates

Started by
1 comment, last by outRider 19 years, 11 months ago
I have a certain source file that uses overloaded new and delete operators. These operators don''t interfere with any other source files because they''re not defined in any other source files and the default new/delete are used. That''s good. However, in this certain source file I''m also using std::vector, and the problem is that templates are instantiated in every source file it''s used in, then merged by the linker. The instance in the source file with the overloads uses the overloaded new/delete operators, which I don''t want. I''ve tried explicitly instantiating vector in another source file, also explicitly instantiating it in the overloaded source file but before including the header that declares the overloads, and neither has worked. Is there a way to somehow work around this? Someone somewhere must have come across overloaded operators and templates in the same translation unit before and been forced to deal with it... ------------ - outRider -
Advertisement
I can think of a couple of ways of getting around this problem:

One, don''t overload ::operator new and ::operator delete in that source file. You can either use malloc()/free() style allocation functions, or per class overloads of new and delete.

Two, since std::vector accepts an allocator argument, create an allocator to pass to the std::vector that bypasses operator new and operator delete, probably by using malloc()/free().

And incidently, your program isn''t well formed. Overloading global operator new and operator delete in a single source file and not other source files engenders undefined behaviour.
The single source-file thing was a simplification to illustrate the problem. I''m actually using the overloads everywhere in my own sources, but I don''t necessarily want library code to use it.

But to clarify further, the overloads are actually part of Paul Nettle''s mmgr. I made some changes to be able to compile it as part of a dll, and since you can''t export overloaded operators I changed his overloads to functions (that are subsequently exported) and defined inlined overloaded new/delete that call the originals, thereby having his mmgr code in the dll exported. The reason for wanting it in a dll is simple, I wanted one instance of the mmgr to deal with allocations in both the executable and any other dlls I''m using, and for that I needed to stick his sources in a dll.

I can''t figure how his original implementation got around this problem through #include ordering, but changing the operators to inline somehow messes things up.

On the flip side I can now track stl allocations with it, not that I really want to... :/

------------
- outRider -

This topic is closed to new replies.

Advertisement