1

I'm not interested in having a static member cluttering up my header as it is only to be used by a free functions in the cpp body. If I declare a static variable here will it only ever occupy the one address just as for a static member?

Apologies but the myriad uses of static in C++ have left me quite unsure.

I am thinking along the lines of:

static Osp::Base::Runtime::Monitor sharedMonitor;
John
  • 6,433
  • 7
  • 47
  • 82

2 Answers2

2

Yes. If you define a static variable at namespace scope, then there is one instance of that variable, accessible within the translation unit in which it's defined.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • I tried the static member way but keep getting random crashes. All examples I've seen require some sort of definition outside the class declaration, but I don't see how I can do that with this class. – John Mar 01 '12 at 18:17
0

First, the word "static" has two meanings in C++: it can refer to the keyword static (which in turn has different effects according to where it is used), or it can refer to the lifetime of a variable: all variables defined at namespace have static lifetime.

From what you say, I think you are looking for a variable with static lifetime, which would not be visible outside the single translation unit where it appears. The preferred way of doing this is to define a variable in an unnamed namespace:

namespace {
int myWhatever;     //  No keyword static...
}

Class member variables which are declared static also have static lifetime, as do local variables (inside a function) which are declared static.

Such a variable is accessible everywhere after its definition in the translation unit, but no where else. It has a single instance, which comes into being at the start of the program, and lasts for as long as the program runs. If it has a constructor, the constructor will be called before main (or when the dynamic object is loaded, if dynamic linking is used), and it's destructor will be called after exit has been called (or when the dynamic object is unloaded, if dynamic linking is used).

With regards to threads, C++11 has a storage class specifier thread_local: variables declared with this specifier have one instance per thread, with a lifetime which is the equivalent of that of the thread. It will be initialized (constructed) before first use, and destructed when the thread exits. This is something different from static.

James Kanze
  • 150,581
  • 18
  • 184
  • 329