CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2010
    Posts
    54

    Pass more parameter in overriding new operator

    I want to override new operator in C++, by following the instructions at http://www.cprogramming.com/tutorial/operator_new.html

    class CMyclass
    {
    public:
    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);

    Thanks

  2. #2
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    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.
    Code:
    class CMyClass
    {
    public:
      CMyClass* Allocate(BOOL bUseWhichMemManager) { return new CMyClass(bUseWhichMemManager); }
      // may also want a deallocator function
      //void Deallocate(CMyClass* p); { delete p; }
    
    
    private:
      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
  •  





Click Here to Expand Forum to Full Width

Featured