std::cout 如果从自定义分配器 (Visual Studio 2019) 调用,则不会输出

std::cout does not output if called from custom allocator (Visual Studio 2019)

本文关键字:调用 输出 2019 Visual 如果 cout 自定义 分配器 std Studio      更新时间:2023-10-16

我正在尝试研究如何使用自定义分配器。我编写了一个继承自 std::allocator 的基本分配器,并使用 std::cout 尝试跟踪其执行。这是代码:

#include <vector>
#include <iostream>
struct myIntAllocator : std::allocator<int>
{
int* allocate(size_t size)
{
std::cout << "bar" << std::endl;
return new int[size];
}
};
int main()
{
std::cout << "foo" << std::endl;
std::vector<int, myIntAllocator> ints;
ints.push_back(1);
}

输出:

foo

我希望它也输出bar,但这没有出现。

我是否缺少一些以这种方式std::cout工作的魔力?还是我误解了如何使用分配器?

我在Visual Studio 2019中使用MSVC v142,编译器优化关闭。

你问:

我是否缺少一些让 std::cout 以这种方式工作的魔力?或有 我误解了如何使用分配器?

在某种程度上,是的 - 通常您不想继承和重载分配器,因为这只会使事情变得更加混乱并使您面临切片/向上投射。另一点是,就我们所知道的,向量或分配器可能有一些我们不知道的实现细节。逻辑解释仍然是你的函数不会被调用。