[llvm-dev] Question about std::map

David Blaikie via llvm-dev llvm-dev at lists.llvm.org
Thu Dec 3 16:24:02 PST 2020


On Thu, Dec 3, 2020 at 4:19 PM Paul C. Anagnostopoulos via llvm-dev <
llvm-dev at lists.llvm.org> wrote:

> 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));


>
> _______________________________________________
> LLVM Developers mailing list
> llvm-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20201203/2a3f2688/attachment.html>


More information about the llvm-dev mailing list