c++ - std::map 插入 && 重载导致复制

标签 c++ stl stdmap value-categories

看看这个有趣的演讲:

CppCon 2017: Matt Kulukundis “Designing a Fast, Efficient, Cache-friendly Hash Table, Step by Step”

他在 38:32 分钟左右提到

void Benchmark_Slow(int iters) {
    std::unordered_map<string, int> m;
    std::pair<const string, int> p = {};
    while (iters--) m.insert(p)
}

比下面的变体慢 2 倍

void Benchmark_Fast(int iters) {
    std::unordered_map<string, int> m;
    const std::pair<const string, int> p = {};
    while (iters--) m.insert(p)
}

我还在想为什么 &&将选择重载 (1)。

  • std::pair<iterator,bool> insert( value_type&& value ); (1)

  • std::pair<iterator,bool> insert( const value_type& value ); (3)

哪里value_typestd::pair<const Key, T> .

毕竟,我们没有移动值,所以在我的理解中,表达式 p应该是左值而不是 x/prvalue,对吗?谁能赐教一下?

最佳答案

你不接受有问题的重载:

std::pair<iterator,bool> insert(const value_type& value); // (1)

template< class P >
std::pair<iterator,bool> insert(P&& value); // (2)

P 推导为 value_type&

关于c++ - std::map 插入 && 重载导致复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50398597/

相关文章:

C++ 创建类对象

C++ - 如何让多个线程写入一个文件

c++ - 使用 Maps 和 make_pair 编译错误

c++ - openMp:并行化 std::map 迭代

c++ - Qt - 无法访问动态创建的 QHBoxLayout 小部件

c++ - LLVM传递计数 vector 类型指令

c++ - 具有 STL C++ 错误的强连接组件?

c++ - 使用依赖于 "this"c++ 的比较结构初始化一个集合

c++ - 成员函数作为 map 比较器?

c++ - 从 out_of_range 异常中获取 key