gpt4 book ai didi

c++ - emplace_back 导致静态 constexpr 成员上的链接错误

转载 作者:行者123 更新时间:2023-12-03 12:51:49 24 4
gpt4 key购买 nike

为什么emplace_back采用需要定义的成员的引用? emplace_back(整数文字)emplace_back(static constexpr 整数成员) 之间有什么区别?

如果我切换到 C++17,它编译得很好。我发现在 C++17 中 static constexpr 数据成员隐式 inlined 。这是否意味着编译器隐式地为它们创建了一个定义?

示例代码:

class base {
int n;
public:
base(int n):n(n) {}
};

struct base_trait {
static constexpr int n = 1;
};

int main(void) {
vector<base> v;
v.emplace_back(1); // ok
v.emplace_back(base_trait::n); // link error with -std=c++14, ok with -std=c++17
return 0;
}

最佳答案

正如您所说,emplace_back 通过引用获取参数,因此传递 base_trait::n 会导致其为 odr-used .

an object is odr-used if its value is read (unless it is a compile time constant) or written, its address is taken, or a reference is bound to it;

在 C++17 之前,这意味着这里需要定义 base_trait::n 。但自 C++17 起,行为发生了变化,为 constexpr static data member不再需要类外定义。

If a const non-inline (since C++17) static data member or a constexpr static data member (since C++11) is odr-used, a definition at namespace scope is still required, but it cannot have an initializer. This definition is deprecated for constexpr data members (since C++17).

A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify an initializer. It does not need an out-of-class definition. (since C++17)

关于c++ - emplace_back 导致静态 constexpr 成员上的链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61917766/

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