How to distinguish classes that are allocated using a memory pool

In the project, I have two types of classes:

  • Type A: normally distributed classes that I manage with std::unique_ptr<>
  • Type B: classes whose new ones were overridden to allocate memory from increase memory pool

For the latter, proper use is a call to a new one, as usual, to place a new instance, but never calling delete. These objects are cleared when the memory pool object goes out of scope.

Therefore, if I accidentally store an instance of type B in std::unique_ptr<> , I will get a segmentation error. Similarly, calling explicitly on a type B pointer would be a bad idea.

What types of C ++ mechanisms should be used to prevent these types of errors from occurring?

As a simple but ugly fix, I am thinking of renaming all my Type B classes to have a prefix like MP (for the memory pool), so I visually know not to stuff them inside std :: unique_ptr <>.

However, it would be very desirable to have a language mechanism that can catch problems during compilation or at least die in a more obvious way if I or other members of my team accidentally make such errors.

+4
source share
2 answers

Well, I see boost in the memory pool, there is one function called is_from() that reports whether this memory is from the pool or not. Having said that, you can override the delete operator, where you can check if the memory is from the boost memory pool, then delete it only if it is not from the pool. You can also use a custom div for std::unique_ptr if it helps you in any way.

+5
source

You must also override operator delete .

+3
source

Source: https://habr.com/ru/post/1399416/


All Articles