Link to home
Start Free TrialLog in
Avatar of Aidman
Aidman

asked on

private overloading of new & delete

Hi

I have been looking at some custom memory management and I am curious about new/delete overloading. I would like to know if one can limit overloaded new & delete operators to a template specific class (meaning all de-/allocations of all types occurring in the class are using the overloads). And also subject the overloads to the template for that class so different class variants use different overloads, while those overloads do not affect any code outside the given class. To give some more clarity se the example “code” below:

template <class Allocator>
class Dummy {
private:
      
      // the operators should only be used by the class itself.
      // assume Allocator is a class supplied with the necessary functions

      void *operator new (size_t size) {
            return Allocator::allocSomeMemory(size); // call template specific function
      }

      void operator delete (void *ptr) {
            Allocator::deallocTheMemory(ptr); // call template specific function
      }

public:

      void foobar() {
            int *x = new int; // calls the overloaded new operator.
            // please note that the allocated object could be of any type,
            // including classes

            delete x; // calls the overloaded delete operator
      }
};

Unfortunately this code won’t compile and even if it would the overloads would only be called when de-/allocating the Dummy class, which is not desirable.
Avatar of jkr
jkr
Flag of Germany image

Binding 'new' and 'delete' to a class IMHO does not really make sense anyway, since these operators are required to be accessible at 'global scope', i.e. 'outside' your class. What you can do is providing/defining operators that in return use your allocators.
ASKER CERTIFIED SOLUTION
Avatar of rendaduiyan
rendaduiyan
Flag of China image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of _corey_
_corey_

Correct me if I'm wrong, but class specific new and delete overloads are static members so it shouldn't affect what variation of that class you're using.

corey
> class specific new and delete overloads are static members.
That they are.

> the overloads would only be called when de-/allocating the Dummy class
Precisely, which is why it's not a good solution for you.

> meaning all de-/allocations of all types occurring in the class are using the overloads
These operator new/delete act on type, not scope. If scope is truely what you after then jkr's suggestion of providing allocation/deallocation routines other than operator new/delete is a tidy solution.


It is possible to re-implement the global opertor new/delete pair but this is not what you want either, as *every* memory request would be handed by these.