Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how safe are self registering classes?

Coming from this thread I implemented a similar system in c++ to the chosen solution there.

My problem now is that it is stated there by the user Daniel James that this solution might not work with every compiler (I'm using gcc currently) and is not defined in the c++ standard.

Suppose I have an abstract base-class for the interface and a factory-class as a singleton that stores pointers to a function that constructs the specific classes derived from that interface.

then I have a helper class that looks roughly like this:

base.hpp

...
class implRegistrator {
    public:
        implRegistrator(constructPointer) {
            factory::registerImpl(constructPointer);
        };
}

And an implementation that (through a macro) creates an object of this class to register itself:

impl1.cpp

...
implRegistrator* impl1 = new implRegistrator(getConstructPointer());

How compatible to the C++ standard is this solution? Is it safe to assume that the class instantiation ind impl1.cpp will even happen, since nothing from the main program will actually explicitly call it at compile-time?

Thanks in advance for any answers.

like image 401
Ragas Avatar asked Apr 29 '14 09:04

Ragas


1 Answers

So after looking a bit further into the standard at the position where Angew pointed me before, I noticed footnote 34 in [basic.start.init]§4 of the standard that states:

A non-local variable with static storage duration having initialization with side-effects must be initialized even if it is not odr-used (3.2, 3.7.1).

And that actually addresses the problem which is mentioned here. The self registering class is not odr-used and modifies the state of the factory object, thus having an initialization with side-effects.

So per this footnote it is actually safe to do a self registration like the one mentioned by me and Skizz.

Edit: As Matt McNabb mentioned, I shouldn't have relied on the footnote. So here is the part of the specification that the footnote refers to: [Basic.stc.static] §2

If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8.

like image 57
Ragas Avatar answered Sep 20 '22 01:09

Ragas