std::map calls default constructor on [], copy constructor on insert()

家住魔仙堡 提交于 2020-01-05 06:40:12

问题


My std::map is called uniformBlocks. I was testing out the way to add new elements when I noticed something weird. When I add new key, value pair using the method below:

uniformBlocks["MatrixBlock"] = matrixBlock;

The default constructor is called. However, when I use insert, the copy constructor is called, which is expected.

uniformBlocks.insert(
    std::pair<const std::string, glWrapper::UBO>("MatrixBlock", matrixBlock)
);

Why is there a difference between the two methods. Aren't they implemented the same way under the hood?


回答1:


[] creates an object if it does not exist then returns a reference to it. At that time, no arguments are available.

= then assigns to this reference.

insert has no need to do that. It can simply construct in place using the pair you pass in.

With careful use, emplace can even do away with the copy or move ctor call.



来源:https://stackoverflow.com/questions/50770098/stdmap-calls-default-constructor-on-copy-constructor-on-insert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!