简体   繁体   English

重载C ++中的new运算符

[英]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. 我想尝试使用运算符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. 1] 20 2] 12 3] 15 4] 6 5] 23。 which ever minimum amount fits to the objects size(eg.21) 最小的量是否适合对象的大小(例如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: 如果要对程序中的所有类型使用new运算符,只需覆盖全局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. 您将必须使用该类型显式使用它,或者可以使用factory或factory方法在堆上创建该类的实例,并将该实现隐藏在内部。

You can override operator new for classes using it as a static method: 您可以将它用作静态方法来覆盖类的new运算符:

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. 然后,将使用该重载运算符来创建该类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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