Friday, July 15, 2022

Watch out for vector one argument constructor

vector constructor

 Aggregate initialization brought us many good things. There is though one nasty pitfall with std::vector. std::vector can be initialized with a size_t to specify its initial size. There is a potential ambiguity since the vector also accepts size_t as its element type:


#include <cassert>
#include <vector>

int main()
{
   std::vector<size_t>  vec0(5);   // vector size is set
   std::vector<size_t>  vec1{5};   // vector size isn't set directly but vector is initialized with 1 element

   assert(vec0.size() == 5);
   assert(vec1.size() == 1);

   std::vector<size_t>  vec2{vec0.size()};  // even worse: vectors do not have the same size now

   return 0;
} 

This is especially a problem with 32 bits code where size_t is an int typedef. A solution is that the C++ committee resolves the ambiguity e.g. by introducing a 2 argument overload for vector constructor (with an extra enum). Until then it's watching out 

Reference:

No comments:

Post a Comment

C++ horrible aspects

C++ horrible aspects  Linus Torvalds described C++ as being a horrible language. While C++ has its dark corners I choose it any day ove...