Question about std::map

I have the following map:

  std::map<std::string, std::vector<Record *>> ClassRecordsMap;

I call a function that builds a new vector of <Record *> and returns it.

  const auto Records = getAllDerivedDefinitions(makeArrayRef(ClassName));

What is the best way to add it to the map, being careful not to copy it? This is what I'm doing now:

  ClassRecordsMap[ClassNameString] = std::move(Records);

I have the following map:

std::map<std::string, std::vector<Record *>> ClassRecordsMap;

I call a function that builds a new vector of <Record *> and returns it.

const auto Records = getAllDerivedDefinitions(makeArrayRef(ClassName));

This would be one of the times where using top level const on local variables will make things less good. You can’t move from Records if it’s const like that. (generally I don’t think it’s practical to use top level const in C++ pervasively - so I’d suggest generally not doing it, because doing it only sometimes may make things harder to read (“why is /this/ particular local variable const when lots of others aren’t?” the future reader will ask themselves))

What is the best way to add it to the map, being careful not to copy it? This is what I’m doing now:

ClassRecordsMap[ClassNameString] = std::move(Records);

Yep, generally that’ll do it.

If you want to avoid even a default construction of std::vector (it’s cheap, there’s unlikely to be any reason to avoid that) you could use emplace:

ClassRecordsMap.try_emplace(ClassNameString, std::move(Records));

This just got weird. The 'const' was left over from previous experiments, so I removed it. Now when I run the -gen-instr-info backend on the AMDGPU target, I get:

error: ERROR: No 'Target' subclasses defined!

This suggests that there is a fundamental flaw somewhere. That message would be explained if the records pointed to by the vector of <Record *> were disappearing after the vector is stored in the map.

This just got weird. The ‘const’ was left over from previous experiments, so I removed it. Now when I run the -gen-instr-info backend on the AMDGPU target, I get:

error: ERROR: No ‘Target’ subclasses defined!

This suggests that there is a fundamental flaw somewhere. That message would be explained if the records pointed to by the vector of <Record *> were disappearing after the vector is stored in the map.

The try_emplace solution would only work if the key mapping wasn’t already present in the map. If it is already in the map, then the x[y] = z approach would be what you want.