Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is destructor of `boost::multi_array_ref` non-virtual?

The relationship among const_multi_array_ref, multi_array_ref and multi_array is as follows:

  • multi_array_ref is derived from const_multi_array_ref
  • multi_array is derived from multi_arry_ref

However, the destructors of const_multi_array_ref and multi_array_ref are non-virtual. In fact they do not have an explicitly implemented destructor. Only multi_array has a one. Does this imply the following usage is not recommended?

multi_array_ref<float, 2> * = new multi_array<float, 2>(extents[3][3]);

If so, why?

like image 604
Danqi Wang Avatar asked Nov 04 '22 18:11

Danqi Wang


1 Answers

multi_array library classes aren't designed for dynamic polymorphism. They don't have any virtual functions, so it doesn't look reasonable to make destructor virtual too. It's common STL-like design, multi_array_ref is just used as unified interface adapter for data owning and non-owning cases.

Your usage sample is highly not recommended - it will lead to memory leak because multi_array destructor will not be executed on delete call.

But it will be safe to access multi_array instance via reference or pointer to multi_array_ref.

like image 159
Rost Avatar answered Nov 12 '22 20:11

Rost