gpt4 book ai didi

c++ - g++ 可变参数模板问题

转载 作者:可可西里 更新时间:2023-11-01 16:06:12 25 4
gpt4 key购买 nike

所以我把这个程序交给了 g++ 和 clang(都在 Linux,x86_64 上):

#include <iostream>

using namespace std;

template<char... Cs>
struct A {
static const string s;
static A a;
~A() {
cout << "s = " << s << "\n";
}
};

template<char... Cs>
const string A<Cs...>::s = {{Cs...}};

template<char... Cs>
A<Cs...> A<Cs...>::a;

int main(void)
{
(void)A<'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'>::a;

return 0;
}

Clang 输出 s = aaaaaaaaaaaaaaaa (正如预期的那样)。

g++(版本 5 到 8)输出 s = s = aaaaaaaa (非常出乎意料)。

如果您不使用可变参数模板(如果您删除所有 <> 代码并内联字符列表以初始化 A::s ,则不会发生这种情况。

如果您替换 std::string 也不会发生这种情况通过字符数组(并使用 A<Cs...>::s = {Cs...} 代替)。

这段代码不是故意的,还是编译器错误?

最佳答案

您的代码不正确。标准的重要部分是 6.6.3/1 [basic.start.dynamic]在 N4659 中:

Dynamic initialization of a non-local variable with static storage duration is unordered if the variable is an implicitly or explicitly instantiated specialization [...]

因为初始化是无序的,所以不能依赖销毁的顺序。任何顺序都是合法的,不管构造顺序如何。参见 6.6.4/3 [basic.start.term]

因此允许 gcc 在销毁 a 之前销毁 s,这就是发生的事情并导致奇怪的输出。 Live .

关于c++ - g++ 可变参数模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50339063/

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