Static template data members storage

前端 未结 2 476
别跟我提以往
别跟我提以往 2021-01-07 05:51

First I\'ll write example to properly address the question.

First of all, I\'ll declare template to be used to create singleton object (not auto-created): singlet

相关标签:
2条回答
  • 2021-01-07 06:10

    The answer to this is the same as with any other template-based or inline function - the only difference is in this case the variable ends up being marked for placement in a read-write section.

    In most compilers, the compiler will instantiate any needed template functions and static member variables in every compilation unit they are referenced in. The compiler will also mark these as 'weak symbols'; this means that, at the final link phase, the linker will choose one of the emitted copies arbitrarily to go into the final executable.

    Note, however, that the weak symbol consolidation process is usually done at the static linking stage. The dynamic linker will not do this for you. As such, you should avoid having mutable (read-write) template static data members in shared libraries. Also avoid address comparisons on read-only template static data members across shared libraries (including RTTI data).

    And keep in mind in general with shared libraries that almost any change in template definitions that cross the ABI boundrary will break your ABI - so it's probably best to avoid templates entirely in shared library APIs!

    0 讨论(0)
  • 2021-01-07 06:19

    Though I may misunderstand your question, if storage in your question means definition, my answer might apply.
    As for one definition rule, 3.2 p5 of the standard says:

    There can be more than one definition of ... static data member of a class template ... in a program provided that each definition appears in a different translation unit,

    and

    If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D.

    There are some requirements for this rule. In this question's case, since the variable is initialized by an integral constant 0, the requirements are satisfied.

    0 讨论(0)
提交回复
热议问题