内联静态 constexpr 与全局内联 constexpr
假设我在头文件中有一些 inline constexpr
变量(名为 default_y
和 default_x
),并且我决定将它们移动到一个类中它们完全相关并将它们标记为静态
(因为它在设计方面看起来更好)。
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
};
}
所以问题是这会对程序启动时初始化它们的方式和时间(以及整体效率)产生影响吗?此特定用例中的 inline
关键字是否会强制编译器为这两个变量添加一些保护并使访问它们变慢?或者也许因为它们是 constexpr ,所以不需要在运行时执行这些操作,因为可以从可执行文件的只读部分检索它们的值,然后在开始时将其分配给它们主线程?
我使用 inline static
构建了一次程序,又使用 static
构建了一次程序,与之前的解决方案相比,二进制文件的大小没有差异,因此链接器可能生成了完全相同的文件代码(希望如此)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
放置静态内联 constexpr 变量不应以任何方式影响效率。由于 constexpr,如果可能的话,它们会在编译时进行 const 初始化。这里的
inline
关键字帮助您初始化类
体内的static
变量。您可能会发现有关inline
关键字的材料很有趣:https://pabloariasal.github.io/2019/02/28/cpp-inlined/Placing
static inline constexpr
variables should not impact efficiency in any way. Due toconstexpr
they're const-initialized at compile time if it's possible.inline
keyword here is helping you to initializestatic
variable inside the body of aclass
. You might find this material on theinline
keyword interesting: https://pabloariasal.github.io/2019/02/28/cpp-inlining/