Thread: Overloading operator new

  1. #1
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343

    Overloading operator new

    Iīve been reading about overloading the new operator in classes and I canīt get a thing. Lets say I declare a class

    Code:
    class Test
    {
    public:
    void *operator new (size_t);
    private:
    };
    and a pointer to a Test class

    Code:
    Test *pToTest = new Test;
    Does this allocate memory on the heap(implicity) or do I have to do it explicity in the member-function new
    Code:
    void * Test::operator new(size_t howbig)
    {
    //Envoke global new() to allocate ???
    //and extra stuff
    }
    I would also appreciate if someone could give me an example when this kind of overloadning would be appropriate. Is this used to create some kind of "smart" pointer or what, becuase I have always been satisfied with the global new().

  2. #2
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378

    I think this is what your looking for...

    "Be formless, shapeless, like water... You put water into a cup, it becomes the cup, you put water into a bottle, it becomes the bottle, you put it in a teapot, it becomes the teapot... Now water can flow, or it can crash, be water my friend."
    -Bruce Lee

  3. #3
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    Interesting, but what is a memory pool ???

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Basically, when you call new on an object, a few actions take place....one of which is a call to "operator new()". Now, there's a global version of this function that works just like the C function malloc (stecify the size and get a void* return)....but if you overload "operator new", then new calls your implementation instead of the global version. So its possible for you to allocate a whole load of memory at the start of your program (as a memory pool), and then release part of this memory every time a new instance of your class is made with a call to new.....this is good if you are worried about availability of memory throughout the program and you dont want to risk successive bad_alloc exceptions

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading operators
    By ugmusicbiz in forum C++ Programming
    Replies: 2
    Last Post: 02-13-2009, 01:41 PM
  2. unary operator overloading and classes
    By coletek in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2009, 02:14 AM
  3. Overloading operator ==
    By anon in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2006, 03:26 PM
  4. operator overloading
    By blue_gene in forum C++ Programming
    Replies: 6
    Last Post: 04-29-2004, 04:06 PM
  5. overloading
    By theLukerBoy in forum C++ Programming
    Replies: 6
    Last Post: 11-04-2002, 08:49 PM