0

I have a code for best fit algorithm. I want to try to use the best fit algorithm using the operator new.

Every time I create an object I should give it from the already allocated memory say,

1]20 2]12 3]15 4]6 5]23 respectively. which ever minimum amount fits to the objects size(eg.21)

I wanted to do it for different object types, so I need to write the overloaded operator new to be common functionality for all the class objects.

Can I do it through friend functions, or is there any possible way to do.

Angus
  • 12,133
  • 29
  • 96
  • 151
  • You can override the global new operator and also lookup placement new. – legends2k Oct 21 '13 at 04:34
  • There is some good information in the [c++-faq](http://stackoverflow.com/questions/tagged/c++-faq): [Overloading new and delete](http://stackoverflow.com/questions/4421706/operator-overloading/4421791#4421791) – Chris Olsen Oct 21 '13 at 05:41

1 Answers1

1

If you want to use your operator new for all types in your program simply override global operator new:

void* operator new  ( std::size_t count );
void* operator new[]( std::size_t count );
void* operator new  ( std::size_t count, const std::nothrow_t& );
void* operator new[]( std::size_t count, const std::nothrow_t& );

If you want to do it only for certain classes you have 2 possibilities:

Use placement operator new:

void* operator new  ( std::size_t, void* ptr );
void* operator new[]( std::size_t, void* ptr );

You will have to explicitly use it with that types, or you can use factory or factory method to create instances of that classes on the heap and hide that implementation inside.

You can override operator new for classes using it as a static method:

class FooBar {
public:
   static void* operator new  ( std::size_t count );
   static void* operator new[]( std::size_t count );
};

Then that overloaded operator will be used to create instances of that class.

Slava
  • 43,454
  • 1
  • 47
  • 90
  • [Operator new override is always static by standard](http://stackoverflow.com/a/5406262/183120) so you can safely remove static. – legends2k Oct 21 '13 at 04:35
  • @legends2k Thanks, but I think in some cases show that explicitly would not hurt (like we can omit virtual on derived methods, but it better not to IMHO) – Slava Oct 21 '13 at 04:38