没有优化的 g++ 4.9 上静态 constexpr 的未定义引用

undefined reference for static constexpr on g++ 4.9 with no optimisation

我有以下代码:

#include<chrono>
#include<iostream>

using namespace std::chrono_literals;

#define MSG "hello"
#define DUR 1000ms

class mwe{
    public: 
    static constexpr auto msg = MSG;
    static constexpr auto dur_1 = DUR;
    static constexpr std::chrono::milliseconds dur_2 = DUR;
    static const std::chrono::milliseconds dur_3;
    static constexpr decltype(DUR) dur_4 = DUR;
};

constexpr std::chrono::milliseconds mwe::dur_2; 
const std::chrono::milliseconds mwe::dur_3 = DUR; 
constexpr decltype(DUR) mwe::dur_4;

int main(void) {
    std::cout << "str: " << mwe::msg << std::endl;
    std::cout << "dur_1: " << mwe::dur_1.count() << std::endl;
    std::cout << "dur_2: " << mwe::dur_2.count() << std::endl;
    std::cout << "dur_3: " << mwe::dur_3.count() << std::endl;
    std::cout << "dur_4: " << mwe::dur_4.count() << std::endl;
}

如果我编译它 (g++ 4.9),通过

g++ -std=c++14 -O2 test.cpp

一切都按预期工作,但如果我通过

编译它
g++ -std=c++14 -O0 test.cpp

我收到以下错误:

undefined reference to `mwe::dur_1'

我个人喜欢这种方式,dur_1 被定义和声明最多,但如果没有启用优化,它在我的版本中不适用于 g++。 因为我知道的所有其他方式(dur_2、dur_3、dur_4)都有其缺点(值冗余,没有自动类型推导,例如,如果我将 1000ms 更改为 1s,aso .)

您知道吗,如果这是一个 gcc 错误,那么编译可以在生产模式下运行,但如果不进行优化就无法运行?

是否有另一种可能的方法来实现此功能,而无需在 class 之外定义 dur_x 的位置?

这不是您的编译器中的错误。

odr-used dur1 但从未定义过它。而且,constexpr 和内联初始化程序都没有将该声明作为定义。

[C++11, C++14: 9.4.2/3]: If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

一如既往,优化级别可能会影响编译器and/or愿意报告此类错误的程度。

您可以编写以下内容来定义您的成员:

#include<chrono>

using namespace std::chrono_literals;

#define DUR 1000ms

struct T
{
   static constexpr auto dur_1 = DUR;
};

constexpr decltype(T::dur_1) T::dur_1;