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

时间:2011-10-02 21:15:28

标签: c++ gcc c++11

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

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

有以下测试程序:

#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等。)

1 个答案:

答案 0 :(得分:4)

查看带有/不带g++ ... -S的{​​{1}}的输出,看来在使用-fwhole-program时根本不会发出整个自定义新/删除运算符。

我开始怀疑我们在这里看到一个错误。