mardi 29 septembre 2015

Why doesn't the compiler warn about unsigned to signed conversion?

I recently got bit in the butt with this code:

std::size_t s = 10;
std::vector<int> v{s};

Rather than initialize with a size of 10, this initializes with a size of 1 with one element 10. However, the vector has an explicit constructor that takes a std::size_t. With all the hype about "use braces everywhere", I would expect many people have fallen into this trap. This could be avoided if the compiler simply warned that we were trying to turn a size_t into an int.

Why isn't the compiler required to do this?

EDIT: My original code had const std::size_t s. Apparently none of the compilers I use warn unless I remove the const. Is this a bug?

Aucun commentaire:

Enregistrer un commentaire