gpt4 book ai didi

c++ - 静态 constexpr 成员的 undefined reference 错误

转载 作者:IT老高 更新时间:2023-10-28 23:10:48 28 4
gpt4 key购买 nike

考虑这段代码:

#include <vector>

struct A {
static constexpr int kDefaultValue = -1;
std::vector<int> v;
A(int n): v(n, A::kDefaultValue) {}
};

int main() {
A(10);
return 0;
}

链接失败(llvm clang,gcc 4.9,都在 OS X 上):

Undefined symbols for architecture x86_64:
"A::kDefaultValue", referenced from:
A::(int) in main.cpp.o
ld: symbol(s) not found for architecture x86_64

问题是它有什么问题?它可以通过 static_cast-ing A::kDefaultValueint 来修复。或者将 kDefaultValue 移出 A。这两种情况似乎都很丑陋。这是使其链接的另一种方式吗?

最佳答案

这种行为一次又一次地困扰着我。问题的原因是您的

A(int n): v(n, A::kDefaultValue) {}

odr-uses static constexpr 成员,因为 v 的构造函数采用常量引用第二个参数。 Odr-usage 需要在某处进行定义,即

const int A::kDefaultValue;

在某个编译单元中(编译并链接到 main())。此要求已在 C++17 中删除,相应的定义(如上)已弃用。

但是,定义并不总是可能的(例如对于类模板的成员),避免定义和错误的最简单方法是

A(int n): v(n, int(A::kDefaultValue)) {}

创建一个临时的传递给 v 的构造函数(但由于后者是完全内联的,编译器可能会优化它)。

关于c++ - 静态 constexpr 成员的 undefined reference 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690260/

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