奇怪的GCC数组初始化行为 [英] Weird GCC array initialization behavior
问题描述
当我看到另一个问题(原始代码使用 std :: thread
而不是 std :: vector
,但语法是一样的):
#include< iostream>
#include< vector>
#include< iterator>
#include< algorithm>
int main()
{
std :: vector< double> vecs [10] = std :: vector&Double;(10,1);
for(auto& vec:vecs){
std :: copy(vec.begin(),vec.end(),std :: ostream_iterator< double>(std :: cout, );
std :: cout<< std :: endl;
}
return 0;
}
此代码不应编译; std :: vector< double> vecs [10] = std :: vector< double>(10,1);
是无效的初始化语法,clang使用拒绝它error:array initializer必须是初始化器list
。但是,GCC 接受它,并显示为用指定临时文件的副本初始化列表中的每个向量。 p>
这是我从来没有听说过的某些GCC扩展(不知何故也设法生存 -pedantic-errors
)
我认为这是一个错误。
#include< vector>
int main()
{
std :: vector< double> x = std :: vector&Double;(10,1);
std :: vector< double> vecs [10] = x;
return 0;
}
工作(如您所见)。
While
int main()
{
int x = 10;
int is [10] = x;
return 0;
}
会产生(预期)错误。
I encountered a variant of this code when looking at another question (the original code used a std::thread
instead of std::vector
, but the syntax is the same):
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<double> vecs[10] = std::vector<double>(10, 1);
for(auto& vec: vecs){
std::copy(vec.begin(), vec.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout<<std::endl;
}
return 0;
}
This code shouldn't compile; std::vector<double> vecs[10] = std::vector<double>(10, 1);
is not valid initialization syntax, and clang rejects it with error: array initializer must be an initializer list
. However, GCC accepts it and appears to initialize every vector in the list with a copy of the specified temporary.
Is this some GCC extension I've never heard about (that somehow also managed to survive -pedantic-errors
) or just a plain bug?
I would consider this a bug.
#include <vector>
int main()
{
std::vector<double> x = std::vector<double>(10, 1);
std::vector<double> vecs[10] = x;
return 0;
}
Works (as you have spotted).
While
int main()
{
int x = 10;
int is[10] = x;
return 0;
}
yields the (expected) error.
这篇关于奇怪的GCC数组初始化行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!