Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unordered_map of std::ofstream

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?

like image 381
Walter Avatar asked Jan 26 '26 14:01

Walter


1 Answers

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

like image 143
Bryan Chen Avatar answered Jan 28 '26 02:01

Bryan Chen