C ++ singleton initialization order

I have

class Foo
class Bar

Now I want

Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();

to initialize before

int main()

.

Also i want

Foo::singleton

to initialize before

Bar::singleton

Is there any way to guarantee that?

Thank!

+3
source share
4 answers

See also Initialization Procedure for Static Variables.

For gcc use init_priority:

http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html

It works through different translation units. So your code will read:

Foo* Foo::singleton __attribute__ ((init_priority (2000))) = new Foo();
Bar* Bar::singleton __attribute__ ((init_priority (3000))) = new Bar();

I don’t have gcc right now, so I can’t verify this, but I have used it before. Another simpler and more portable solution is to avoid static initialization and explicitly create singletones in a specific place inside the main one.

// Nothing in static area

void main(void)
{
  // Init singletons in explicit order
  {
    Foo* Foo::singleton = new Foo();
    Bar* Bar::singleton = new Bar();
  }

  // Start program execution
  ...
}

, gnarly , .

+2

(, ), , , . .

, , , ( " " ).

+3
#include <iostream>

class Foo {
public:
  static Foo *singleton ()
  {
    if (foo == NULL)
      foo = new Foo;
    return foo;
  }
private:
  Foo ()
  {
    std::cout << "Foo()\n";
  }
  static Foo *foo;
};

Foo *Foo::foo = NULL;

Foo *singleton = Foo::singleton ();

int
main ()
{
  std::cout << "main()\n";
  return 0;
}

:

Foo()
main()
0

:

// smooth.cpp
#include "foo.h"
#include "bar.h"

Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();

, :

Foo& Foo::singleton()
{
  static Foo Singleton;
  return Singleton;
}

, , singleton , (), , :)

0
source

Source: https://habr.com/ru/post/1733120/


All Articles