How do inline variables work?

前端 未结 3 1587
一个人的身影
一个人的身影 2020-11-22 07:38

At the 2016 Oulu ISO C++ Standards meeting, a proposal called Inline Variables was voted into C++17 by the standards committee.

In layman\'s terms, what are inline v

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 08:21

    Inline variables are very similar to inline functions. It signals the linker that only one instance of the variable should exist, even if the variable is seen in multiple compilation units. The linker needs to ensure that no more copies are created.

    Inline variables can be used to define globals in header only libraries. Before C++17, they had to use workarounds (inline functions or template hacks).

    For instance, one workaround is to use the Meyer's singleton with an inline function:

    inline T& instance()
    {
      static T global;
      return global;
    }
    

    There are some drawbacks with this approach, mostly in terms of performance. This overhead could be avoided by template solutions, but it is easy to get them wrong.

    With inline variables, you can directly declare it (without getting a multiple definition linker error):

    inline T global;
    

    Apart from header only libraries, there other cases where inline variables can help. Nir Friedman covers this topic in his talk at CppCon: What C++ developers should know about globals (and the linker). The part about inline variables and the workarounds starts at 18m9s.

    Long story short, if you need to declare global variables that are shared between compilation units, declaring them as inline variables in the header file is straightforward and avoids the problems with pre-C++17 workarounds.

    (There are still use cases for the Meyer's singleton, for instance, if you explicitely want to have lazy initialization.)

提交回复
热议问题