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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...