Static template data members storage

前端 未结 2 475
别跟我提以往
别跟我提以往 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!

提交回复
热议问题