gpt4 book ai didi

c++ - 带有似乎未被 ODR 使用的静态常量的链接器错误

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

当您深入了解细节时,标准中对 odr-used 的定义非常困惑(至少对我而言是这样)。我通常依赖于“如果采用引用”的非正式定义,except 当左值到右值转换可用时。对于整数常量,它们应该被视为右值,这似乎应该被排除在引用规则之外。这是我无法链接的示例代码:

class Test
{
public:
Test();
static constexpr int MIN_VALUE { 5 };
int m_otherValue = 10;
};

Test::Test()
{
m_otherValue = std::max(m_otherValue, MIN_VALUE);
}

int main()
{
Test t;
}

我得到的链接器错误:

clang++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out/tmp/main-e2122e.o: In function `Test::Test()':main.cpp:(.text+0x2): undefined reference to `Test::MIN_VALUE'clang: error: linker command failed with exit code 1 (use -v to see invocation)

现场样本:http://coliru.stacked-crooked.com/a/4d4c27d6b7683fe8

为什么需要 MIN_VALUE 的定义?它只是文字值的常量,编译器应该将其优化为 std::max(m_otherValue, 5)。所以我就是不明白。

最佳答案

std::max通过引用而不是值来获取其参数。不允许执行左值到右值的转换,然后从该右值构造临时对象。 std::max 可能 正在检查两个参数是否是对同一对象的引用,就编译器所知,并且需要进行检查以评估为 true 如果调用为 std::max(MIN_VALUE, MIN_VALUE)

关于c++ - 带有似乎未被 ODR 使用的静态常量的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31485656/

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