Global non-static variable in an unnamed namespace

I cannot find a good explanation of global non-static variables in an unnamed namespace. I avoid global variables as much as I can. In this particular case, I am only interested in behavior from a purely theoretical point of view.

Assume the following code:

In ah

namespace ai {
  class Widget {
    void DoSomething(int param);
  };
}

In a.cc

namespace {
  int x;
  void Helper() {
  }
}

namespace ai {
  void Widget::DoSomething(int param) {
    x = param;
    Helper();
  }
}
  • If I created two instances of the same Widget class, would both instances have the same x variable?

  • Is the above behavior the same if the class instances are on the same thread against different threads?

  • What if the variable x is instead of the built-in type?

  • When will the variable x be processed and when will it be destroyed?

  • Is there any relation between sizeof (Widget) and such variables?

  • What aspects are defined in the C ++ standard, and what not?

, . " " ? , - (, " ++.." ), ?

+3
3
  • , x.
  • , x.
  • , x.
  • .
  • .
  • , 1-4 .

, static: , .

static int x; 
namespace { 
  void Helper() { 
  } 
}

, static ( /)

+4

     Widget,      x?

. . - , .

,           ?

( ).

, x          ?

. ( , ++ UDT.)

x ?

main(), . undefined. . ( ? .) , , .

- sizeof (Widget) ?

X Y ?

++, ?

, . "" , .

+5
  • . "x" , - .

  • . iso ++, . ++ , , . declspec, , .

  • .

  • x - int. undefined/uninitialzied. , main() .

5 6. .

++ : ++ faq lite

0

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


All Articles