简体   繁体   中英

overloading new operator in c++

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM