Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish classes that allocate using a memory-pool

In a project, I have two kinds of classes:

  • Type A: normally allocated classes that I manage with std::unique_ptr<>
  • Type B: classes whose new has been overridden to allocate memory from boost memory pool

For the latter, the proper usage is to call new, like usual, to allocate a new instance, but to never call delete. These objects get cleaned up when the memory pool object goes out of scope.

Therefore, if I accidentally store a Type B instance in an std::unique_ptr<>, I will get a segmentation fault. Likewise, calling delete explicitly on a Type B pointer would be be a bad idea.

What kinds of C++ mechanisms should I use to prevent these types of errors from occurring?

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

However, it would be highly preferable to have a language mechanism which can catch problems during compilation, or at least die in a more obvious way should I or other members of my team accidentally make these types of mistakes.

like image 911
kfmfe04 Avatar asked Feb 21 '23 06:02

kfmfe04


1 Answers

Well, I see in boost memory pool, there is one function called is_from() which tells if a given memory is from the pool or not. Having said that, you can override delete operator, where you can check if the memory is from the boost memory pool, means delete it only if it is not from the pool. You can also use custom deleter for std::unique_ptr if it in some way helps you.

like image 181
Nawaz Avatar answered Mar 03 '23 06:03

Nawaz