mardi 7 juin 2022

c++11 - private constructor still callable

I have somewhat the following definition of a class in MainLoop.h:

class MainLoop {
    private:
        static const MainLoop     &s_instance;
    public:
        static inline const MainLoop &Instance(void) 
            { return s_instance; }
  
    private:
        MainLoop(MainLoop &mp);
        MainLoop(MainLoop &&mp);
        MainLoop &operator=(MainLoop &mp);
        MainLoop &operator=(MainLoop &&mp);
        ~MainLoop();
        MainLoop()
            { printf("Main Loop is created\n"); };
};

And somewhat like that in the source file MainLoop.cpp:

#include "MainLoop.h"

const MainLoop &MainLoop::s_instance( (MainLoop()) );

This code does not compile because the dtor is private in the scope, but if I change it to the whimsical

#include "MainLoop.h"

const MainLoop &MainLoop::s_instance( *( new MainLoop()) );

it then compiles without saying a word and the class is created before the main function is called.

I have to questions:

  1. Why the ctor is called in the second variant while being private?
  2. Why the dtor's access rights are different in the first variant?

Aucun commentaire:

Enregistrer un commentaire