内联静态 constexpr 与全局内联 constexpr

发布于 2025-01-18 05:06:56 字数 839 浏览 1 评论 0原文

假设我在头文件中有一些 inline constexpr 变量(名为 default_ydefault_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

作死小能手 2025-01-25 05:06:56

放置静态内联 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 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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文