I'd like to use a std::unordered_map<unsigned,std::ofstream> but failed. Now I wonder whether this is simply impossible, or a compiler issue, or whether I just didn't get it right. The problem is the insertion of another element:
std::ofstream&get(unsigned key, std::unordered_map<unsigned,std::ofstream>&map)
{
auto file = map.find(key);
if(file==map.end()) {
map.emplace(std::make_pair(key,std::ofstream{})); // <-- trouble here
file = map.find(key);
assert(file!=map.end());
}
return file->second;
}
fails with gcc (4.8.1), because std::ofstream is not copy-constructible.
However, it is move-constructible, so there ought to be a solution, or not? (all I want to insert is a default-constructed std::ofstream). I tried to add
some std::move()s, but that didn't help.
I just noted that the above code does compile with clang 3.4. Isn't this wrong?
you make a pair first then ask map to construct the pair again and cause the problem
try
map.emplace(key,std::ofstream{});
actually, all you need is
std::ofstream&get(unsigned key, std::unordered_map<unsigned,std::ofstream>&map)
{
return map[key];
}
or remove this function... and use map[key]
because map will construct ofstream using default constructor if a non-exist key was used, so it should works like your code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With