Background
When inserting a std::pair<uint64_t, uint64_t>
to a C++ std::map<uint64_t, int>
, neither the compiler nor the program complains, even if the passed values are not possible for the data type uint64_t
.
In other words, the narrowing conversion of std::pair<uint64_t, uint64_t>(2, -2)
isn't working and is defaulting to the map's type std::map<uint64_t, int>
Code
When I compile and execute the following code with g++ -Wall -Wconversion -Wextra -pedantic test/test_wrong_insert.cpp && ./a.out
:
#include<map>
#include<iostream>
void print_map(std::map<uint64_t, int> & m){
std::cout << "The map is now: {";
for (const auto & n: m){
std::cout << '(' << n.first << ',' << n.second << ") ";
}
std::cout << "}\n";
}
int main(){
std::map<uint64_t, int> m;
ret = m.insert(std::pair<uint64_t, uint64_t>(2,-2));
std::cout << "Tried to insert std::pair<uint64_t, uint64_t>(2,-2). ";
std::cout << "Return: " << ret.second << '\n';
print_map(m);
}
Result
... this is the output:
Tried to insert std::pair<uint64_t, uint64_t>(2,-2). Return: 1
The map is now: {(2,-2) }
Question
Why does std::pair<uint64_t,uint64_t> x{-1,-2}
not produce an error, and how do I make it cause an error?
Aucun commentaire:
Enregistrer un commentaire