What to use instead of static variables

in a C ++ program, I need some helper constant objects that will be created once, preferably when the program starts. These objects will be mainly used inside one translation unit, so the easiest way to do this is to make them static:

static const Helper h(params);

But then there is the problem of static initialization , therefore, if it Helperrefers to any other statics (via params), this can lead to UB.

Another point is that in the end I may need to share this object between several units. If I just leave it staticand put the .h file, which will lead to several objects. I could have avoided this by worrying about extern, etc., but it could, in the end, cause the same problems with the initialization order (and not say that it looks very C-ish).

I was thinking about singles, but that would be superfluous due to the template code and inconvenient syntax (for example MySingleton::GetInstance().MyVar) - these objects are helpers, so they should simplify things, and not complicate them ...

In the same C ++ FAQ this option is mentioned :

 Fred& x()
 {
   static Fred* ans = new Fred();
   return *ans;
 } 

Is it really used and considered good? Should I do it this way, or would you suggest other alternatives? Thank.

EDIT: , : , . main, ( ++ 03). , , , main(). , .

+3
4

( , ).

, , local static .

, -, , :

class Singleton
{
public:
  static void DoSomething(int i)
  {
    Singleton& s = Instance();
    // do something with i
  }


private:
  Singleton() {}
  ~Singleton() {}

  static Singleton& Instance()
  {
    static Singleton S; // no dynamic allocation, it unnecessary
    return S;
  }
};

// Invocation
Singleton::DoSomething(i);

, , .

class Monoid
{
public:
  Monoid()
  {
    static State S;
    state = &s;
  }

  void doSomething(int i)
  {
    state->count += i;
  }

private:
  struct State
  {
    int count;
  };

  State* state;
};


// Use
Monoid m;
m.doSomething(1);

, "" , , . .

, :

  • ?
  • , main?

. ++ 0x , , , , ... , : / unit test ? . -... ;)

, . , , .

, : ? , . , . , ? , , .

... , ?

, global - , . , .


: , .

:

static int foo() { return std::numeric_limits<int>::max() / 2; }
static int bar(int c) { return c*2; }

static int const x = foo();
static int const y = bar(x);

/, . , static , static .

: as-if . as-if , // , , , . , .

, , , . , , , , .

+5
+2

. - main :

void doSomething(const Helper& h);
int main() {
  const Parameters params(...);
  const Helper h(params);
  doSomething(h);
}

- . , - , , , .

, , FAQ. , , .

0

Helper main? , (?) , 0. main, . , , .

0

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


All Articles