std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数 [英] std::map calls default constructor on [], copy constructor on insert()

查看:54
本文介绍了std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 std::map 被称为uniformBlocks.当我发现一些奇怪的东西时,我正在测试添加新元素的方法.当我使用以下方法添加新的键值对时:

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?

推荐答案

[] 如果对象不存在,则创建一个对象,然后返回对它的引用.那时,没有任何参数可用.

[] 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 不需要这样做.它可以简单地使用您传入的对就地构建.

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

小心使用,emplace 甚至可以消除复制或移动 ctor 调用.

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

这篇关于std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆