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

标签 c++ visual-studio-2019

<分区>

我正在尝试研究如何使用自定义分配器。我已经编写了一个从 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,编译器优化关闭。

最佳答案

你问:

Am I missing some magic to making std::cout work in this way? Or have I misunderstood how to use allocators?

在某种程度上,是的 - 通常您想要继承和重载分配器,因为这只会让事情变得更加困惑,并让您面临切片/向上- throw 。另一点是,就我们所知,vector 或 allocator 可能有一些我们也不知道的实现细节。合乎逻辑的解释是仍然您的函数没有被调用。

关于c++ - 如果从自定义分配器调用,则 std::cout 不输出 (Visual Studio 2019),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57669324/

相关文章:

java - JNI 方法返回旧数据

c++ - MFC 对话框在失去焦点时卡住

tfs - 将 VS2019 与 TFS2018 vnext 构建系统结合使用,无需服务器端解决方法

c++ - 为什么通过GLFW进行的这个简单的OpenGL程序在Intel HD P4600上不起作用?

visual-studio-2012 - Visual Studio 2015-2019 : How do I bring back the old find dialog from VS 2010?

c++ - Qt项目C2872错误,生成的ui文件中符号不明确

c++ - 用于测试 C 和 C++ 分配器的基准?

c++ - 函数签名的错误类型推导

c++ - Visual Studio 2019 v16.3.9 是否完全支持 C++20?

c# - 如何为整个项目启用 C# 8.0 的 Nullable Reference Types 功能