Header only singleton.

page HEADER_ONLY_SINGLETON

ELF_SINGLETON

For clang and gcc, the desired coding pattern is as follows.

  class Foo
  {
    // (a)
    __attribute__((visibility("default")))
    // (b)
    T& get_singleton()
    {
      // (c)
      static T singleton;
      return singleton;
    }
  };

(a) is needed when the code is build with

-fvisibility="hidden" 
to ensure that all instances of (b) are visible to the linker.

What is duplicated in the binary is code, in (b).

The linker will make sure only one instance of all the (b) methods is used.

(c) is a singleton implemented inside a method.

This is very desirable, because:

  • the C++ compiler guarantees that construction of the variable (c) is thread safe.

  • constructors for (c) singletons are executed in code path order, or not at all if the singleton is never used.

OTHER_SINGLETON

For other platforms, header only singletons are not supported at this point.

CODING_PATTERN

The coding pattern to use in the source code is as follows

  class Foo
  {
    OPENTELEMETRY_API_SINGLETON
    T& get_singleton()
    {
      static T singleton;
      return singleton;
    }
  };