Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I currently allocate my memory for arrays using the MS specific mm_malloc. I align the memory, as I'm doing some heavy duty math and the vectorization takes advantage of the alignment. I was wondering if anyone knows how to overload the new operator to do the same thing, as I feel dirty malloc'ing everywhere (and would eventually like to also compile on Linux)? Thanks for any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
323 views
Welcome To Ask or Share your Answers For Others

1 Answer

First of all, it's important to note that new and delete can be overloaded either globally, or just for a single class. Both cases are shown in this article. Also important to note is that if you overload new you almost certainly also want to overload delete.

There are a few important notes about operator new and operator delete:

  1. The C++ standard requires that a valid pointer is returned even if the size passed to it is 0.
  2. There's also operator new[] and operator delete[], so don't forget about overloading those.
  3. Derived classes inherit operator new and its brethren, so make sure to override those.

In Effective C++, item 8, Scott Meyers includes some pseudocodish examples:

void * operator new(size_t size)        // your operator new might
{                                       // take additional params
  if (size == 0) {                      // handle 0-byte requests
    size = 1;                           // by treating them as
  }                                     // 1-byte requests
  while (1) {
    attempt to allocate size bytes;
    if (the allocation was successful)
      return (a pointer to the memory);

    // allocation was unsuccessful; find out what the
    // current error-handling function is (see Item 7)
    new_handler globalHandler = set_new_handler(0);
    set_new_handler(globalHandler);

    if (globalHandler) (*globalHandler)();
    else throw std::bad_alloc();
  }
}


void operator delete(void *rawMemory)
{
  if (rawMemory == 0) return;    // do nothing if the null
                                 // pointer is being deleted
  deallocate the memory pointed to by rawMemory;
  return;
}

For more information, I'd definitely pick up Effective C++.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...