问题
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