Monday, 12 August 2013

Schwarz Counter for a vector

Schwarz Counter for a vector

I am looking at a case where I would have a global static std::vector that
I would need to guarantee is initialized (constructed) before certain
static objects in an assortment of translation units.
When I look up how to handle this I come across two proposed solutions:
Have a static object in a global function that is used in place of a
global static object.
Schwarz Counters
My concern with using a Schwarz counter is that the std::vector will be
initialized twice. From this link I get "A useful technique for ensuring
that a global object is initialized only once and before its first use is
to maintain a count of the number of translation units using it."
How does it work that the global is only initialized once? By my reasoning
it would be initialized twice. Once in the normal course of static
initialization and once when the first instance of the Schwarz counter is
initialized.
On a related note, what would the initialization code look like in the
Schwarz counter constructor? I can only think of using a placement new.

No comments:

Post a Comment