Effective C++(理解new和delete的合理替换时机)


author:

  • luixiao1223
    title: 理解new和delete的合理替换时机

为什么想替换编译器提供的new和delete

  1. 用来检测运用上的错误.
  2. 强化效能(默认的new和delete针对的是通用使用情况,设置中庸)如果想追求极致的效率,则需要自己去现实new和delete
  3. 收集使用上的统计数据

一个例子

static const int signature = 0xDEADBEEF;
typedef unsigned char Byte;
// this code has several flaws — see below
void* operator new(std::size_t size) throw(std::bad_alloc)
{
    using namespace std;
    size_t realSize = size + 2 * sizeof(int);
    void *pMem = malloc(realSize);
    if (!pMem) throw bad_alloc();

    *(static_cast<int*>(pMem)) = signature;
    *(reinterpret_cast<int*>(static_cast<Byte*>(pMem)+realSize-sizeof(int))) = signature;

    return static_cast<Byte*>(pMem) + sizeof(int);
}

这个自定义的new有连个缺陷.

  1. 在失败的情况下没有循环调用new handler.
  2. 字节对齐的问题可能会让程序崩溃.

使用别人写的库.

  1. 商业的
  2. Boost的Pool

总结

  1. 为了检测运用错误
  2. 为了收集动态分配内存之使用统计信息
  3. 为了增加分配和归还的速度
  4. 为了降低缺省内存管理器带来的空间额外开销.
  5. 为了弥补缺省分配器中的非最佳齐位.
  6. 为了将相关独享成簇集中(为了cache的命中率)
  7. 为了获得非传统的行为.(你可能希望获得共享内存等.)
发布了127 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/luixiao1220/article/details/104281422