【问题标题】:static constexpr vs constexpr in function body?函数体中的静态 constexpr 与 constexpr?
【发布时间】:2022-01-14 13:48:03
【问题描述】:

static constexprconstexpr 在函数体内使用时有什么区别吗?

int SomeClass::get(const bool b) 
{
    static constexpr int SOME_CONSTANT = 3;
    constexpr int SOME_OTHER_CONSTANT = 5;

    if(b)
        return SOME_CONSTANT;
    else
        return SOME_OTHER_CONSTANT;
}

【问题讨论】:

  • this 函数内部或 any 函数内部的“任何区别”? constexpr 变量具有某些特性,static 变量也是如此。
  • 我正在寻找这个函数内部的任何区别。因为,我猜如果它们在编译时执行,constexpr,函数声明,一切都会有所不同。

标签: c++ static constexpr


【解决方案1】:

这两个声明的主要区别在于对象的生命周期。在编写问题时,我认为使用 constexpr 而不是 const 会将该对象放入 .rodata 部分。但是我错了。此处的constexpr 关键字仅规定该对象可以在编译时函数中使用。因此,对象实际上是在运行时在堆栈中创建的,并在离开函数体时被销毁。 另一方面,static constexpr 对象是放置在.rodata 部分中的对象。它是在我们第一次调用包装函数时创建的。此外,感谢constexpr,它也可以在编译时使用。

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2019-05-25
    • 1970-01-01
    • 2019-07-05
    • 2019-10-03
    • 2021-04-20
    • 1970-01-01
    • 2017-04-04
    • 2016-07-29
    相关资源
    最近更新 更多