inline static constexpr vs global inline constexpr

1.6k views Asked by At

Suppose that I have a few inline constexpr variables (named as default_y and default_x) in a header file and I decided to move them to a class that they are completely related to and mark them static (cause it seems better in terms of design).

namespace Foo
{

inline constexpr std::streamsize default_size { 160 }; // not closely related to the class Bar

class Bar
{
public:
    inline static constexpr std::uint32_t default_y { 20 }; // closely related to the class Bar
    inline static constexpr std::uint32_t default_x { 20 }; // closely related to the class Bar
};

}

So the question is will this make a difference in terms of how and when they are initialized at the start of the program (and overall efficiency)? Will the inline keyword in this particular use case force the compiler to add some guard for these two variables and make accessing them slower? Or maybe because they're constexpr there is no need to do those stuff at runtime since their value can be retrieved from the read-only section of the executable and then be assigned to them at the start of the main thread?

I built the program once with inline static and once with static and there was no difference in the size of the binary compared to the previous solution so maybe the linker generated the exact same code (hopefully).

1

There are 1 answers

1
Tim Aiwa On BEST ANSWER

Placing static inline constexpr variables should not impact efficiency in any way. Due to constexpr they're const-initialized at compile time if it's possible. inline keyword here is helping you to initialize static variable inside the body of a class. You might find this material on the inline keyword interesting: https://pabloariasal.github.io/2019/02/28/cpp-inlining/