CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 2 of 2

Thread: Pass more parameter in overriding new operator

  1. #1
    Join Date
    Nov 2010

    Pass more parameter in overriding new operator

    I want to override new operator in C++, by following the instructions at

    class CMyclass
    CMyClass(BOOL bUseWhichMemManager);
    void* operator new(size_t);
    void operator delete(void*);

    I create two memory manager called CMemManager1 and CMemMangaer2, using different algorithms to allocate buffer. Now I want to control which memory manager to be used, when calling new.

    I try to add a parameter bUseWhichMemManager to the constructor, but in overrided new function, there are no way to access the parameter. Is there a way to pass more parameters to new operator, such as:

    void* operator new(size_t size, BOOL bUseWhichManager);


  2. #2
    Join Date
    Apr 2000
    Belgium (Europe)

    Re: Pass more parameter in overriding new operator

    You may want to consider a class that constructs new objects for you rather than overriding the new operator.
    You may (or may not) want to combine this with making the constructor private, so all objects are created via the creator function.
    class CMyClass
      CMyClass* Allocate(BOOL bUseWhichMemManager) { return new CMyClass(bUseWhichMemManager); }
      // may also want a deallocator function
      //void Deallocate(CMyClass* p); { delete p; }
      CMyClass(BOOL bUseWhichMemManager);
      //~CMyClass();  may want this, to prevent destruction/deallocation with regular delete p calls rather
      // than calling Deallocate(), it isn't waterproof, but it's obvious enough to stop improper use.
    If you want the allocator to be consumer replacable, consider using an allocator object (or change the class to be a template with an allocator parameter, this has pros and cons),

    You will want some guards for the above solution if you want RAII.

    general tips:
    - avoid overloading new, it's a whole can of worms if you don't understand all the itty bitty details about what goes on behind the scene.
    - if you overload the new operator, you can't provide extra parameters, construction is done with the default constructor. You can 'sort of' get your own explicit constructor using placement new (which is another can of worms).
    - if you overload new, you probably also want to overload the delete operator
    - if you overload new (and delete), you probably also want to overload new[] and delete[].

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)