std::string如何在GCC中使用-fwhole-program分配内存

How does std::string allocate memory in GCC with -fwhole-program?

本文关键字:-fwhole-program 分配 内存 GCC string std      更新时间:2023-10-16

更新:以下问题似乎取决于-fwhole-program选项。

我一直在玩内存分配,我遇到了一个小谜团:在GCC(4.6)中,当我用-fwhole-program[/]编译时,std::string如何分配它的内存[edit] ?

有以下测试程序:

#include <new>
#include <string>
#include <iostream>
#include <cstdlib>
void * operator new(std::size_t n) throw(std::bad_alloc)
{
  void * const p = std::malloc(n);
  if (p == NULL) throw std::bad_alloc();
  std::cerr << "new() requests " << n << " bytes, allocated at " << p << ".n";
  return p;
}
void operator delete(void * p) noexcept
{
  std::cerr << "delete() at " << p << ".n";
  std::free(p);
}
int main()
{
  std::string s = "Hello world.";
}

当我使用任何其他动态容器(使用std::allocator<T>)时,分配器使用::operator new,因此我高兴地看到调试消息。然而,与std::string,我什么也没看到。但是,我确信动态分配发生了,因为我可以用valgrind确认(分配了13个字符串长度的字节)。我浏览了几个源文件和标准,我很确定模板是std::basic_string<T, std::char_traits<T>, std::allocator<T>>,所以我不明白为什么我没有看到来自我替换的分配函数的消息。

有人能解释一下这个难题吗?如何跟踪字符串分配?另外,有没有人可以通过其他编译器运行这个,看看它是否产生任何输出?

(例如:如果我添加std::map<int, int> m { { 0, 1 } };,我有输出new() requests 24 bytes, allocated at 0x8d53028等)

看看g++ ... -S有/没有-fwhole-program的输出,似乎在使用fwhole-program时根本没有发出整个自定义的new/delete操作符。

我开始怀疑这是一个bug