【发布时间】:2019-03-25 22:28:34
【问题描述】:
考虑以下简单示例,我使用std::equal_to 比较两个std::pair<std::string, unsigned>。 operator new 被重载,以便在分配发生时打印一条消息(实时代码here):
#include <functional>
#include <string>
#include <iostream>
// overloaded to see when heap allocations take place
void* operator new(std::size_t n)
{
std::cout << "Allocating " << n << std::endl;
return malloc(n);
}
int main()
{
using key_type = std::pair<std::string, unsigned>;
auto key1 = std::make_pair(std::string("a_______long______string______"), 1);
auto key2 = std::make_pair(std::string("a_______long______string______"), 1);
std::cout << "Finished initial allocations\n\n" << std::endl;
std::equal_to<key_type> eq;
eq(key1, key2); // how can this cause dynamic allocation???
}
我看到的消息是
Allocating 31
Allocating 31
Finished initial allocations
Allocating 31
Allocating 31
比较key1 和key2 时,您可以看到发生了两个分配。但为什么? std::equal_to 的运算符通过 const 引用获取其参数,因此不应进行分配……我错过了什么?谢谢。
【问题讨论】:
-
构建标志/编译器命令行?
-
@Yakk-AdamNevraumont gcc 8.2.0 使用 c++17 和 O2 优化
标签: c++ heap-memory std-pair