Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c++ - Weird GCC array initialization behavior

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...