-1

The idea of using the automatic object deconstruction of Stack allocated objects got me thinking of using the system as a way to initialize and clean up 3rd party libraries.

Example:

#include <libA.h>
#include <libB.h>

namespace library {
 class Wrapper {
    Wrapper() {
         libA_init();
         libB_init();
    }
     ~Wrapper() {
        libB_exit();
        libA_exit();
     }
  }
}
int main() {
    library::Wrapper library;

}

People already argued on SO if the simple use of automatic stack deallocation should be called RAII as RAII withouth the R is simply the way OO works. (Allocation is initialization? Sounds like calling a constructor to me.)

Is this usage a well known antipattern or a good idea to organise code?

salbeira
  • 2,375
  • 5
  • 26
  • 40

2 Answers2

2

You asked :

Is this a well known antipattern or a good idea to organise code?

A good idea. Since it's a ressource managing problem, it's a really clean and neat way of organizing 3rd. party c-style library init/cleanup and one I have seen and used before.

Although there are a few finer points to your example.

First, having more than one in each class, clearly breaks with the "one class one responsibility" principle.

Second, unless theres a good reason not to, the init should be placed outside of main (for example, directly following the class definition).

darune
  • 10,480
  • 2
  • 24
  • 62
  • Would placing the initialization as global objects not break my control over when which library gets initialized (like when multiple depend on each other like first initializing glfw for OpenGL, then creating a glfw window that's need to be made current to then initialize the GLAD library to load function pointers etc. etc.) – salbeira Jan 08 '19 at 08:44
  • @salbeira it would and then you may have a reason and be fine with having the code run in main, however there exists other solutions particular to this problem (ie. controlling "static initialization order"). – darune Jan 08 '19 at 08:47
  • 1
    As long as all the different objects depending one on another are defined in the same compilation unit, order of initialisation is the order of definition! You only risk trouble if you distribute the objects over different compilation units. – Aconcagua Jan 08 '19 at 09:09
0

Is this a well known antipattern or a good idea to organise code?

Totally depends on the scope you need to do that.

In general RAII isn't an antipattern, but the preferred pattern to use with c++.

You probably need to take care of the automatically generated copy constructors and assignment operators for library::Wrapper and you may delete those explicitly.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190