11

As an example, consider this header:

#include <iostream>

template<bool = true>
struct A {
    A() {
        static int x;
        std::cout << &x << "\n";
    }
};

static A<> a;

What if I had two different C++ files including this file - would it print the same address twice, guaranteed? Even more importantly, if x was an object of a different type with a non-trivial constructor, would it be guaranteed to only be run once?

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
orlp
  • 112,504
  • 36
  • 218
  • 315
  • I think thats how singleton pattern are implemented, by return a static variable inside `getInstance` – Bryan Chen Dec 10 '13 at 02:40
  • @BryanChen Well that was kind of my plan with this (https://gist.github.com/nightcracker/7884976). Still thinking about thread-safity pre-C++11. – orlp Dec 10 '13 at 02:43

1 Answers1

6

The standard [C++11 14.8/2] says

Each function template specialization instantiated from a template has its own copy of any static variable.

I assume (and sincerely hope) that member functions of a template class are treated the same way, although I can't find the specific language that says so.

In any case, apart from the usual risks associated with initialising static variables in a multithreaded context, I'm sure this would be fine. A<true>::A() (and the internal "static int A<true>::A::x") would be marked as weak symbols and one version would be picked at link time, the same as any other template. (Obviously, an instantiation of A<false> would be distinct from A<true>.)

Edit for comment:

The worry about different translation units seems to be covered by section [3.2/5], defining the ODR:

If D is a template and is defined in more than one translation unit, then... [providing the definitions are identical]... the program shall behave as if there were a single definition of D.

The actual requirements are a bit more language-lawyery (dependent names at the point of instantiation must be the same, etc etc), but I think this is the bit that puts you in the clear :-)

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
  • 1
    I'm slightly confused right now, your quote talks about different specializations, while I'm worried about different translation units (let's assume that the bool is and will always be true). – orlp Dec 10 '13 at 02:47
  • @nightcracker Added another bit of standardese that I think covers that :-) – Tristan Brindle Dec 10 '13 at 02:58