gpt4 book ai didi

c++ - 没有优化的 g++ 4.9 上静态 constexpr 的 undefined reference

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:10 25 4
gpt4 key购买 nike

我有以下代码:

#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 错误,编译可以在生产模式下运行,但如果没有优化就无法运行?

是否有另一种可能的方法来实现此功能,而无需在类外定义 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.

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

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

#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;

关于c++ - 没有优化的 g++ 4.9 上静态 constexpr 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com