void *operator new( size_t, void *p ) throw() { return p; }这个是堆内存进行分配调用。
如果需要对内存分配进行不同的分配策略,则需要重载operator new。这样做,我们可以预先分配好一大块内存,按照程序需求进行管理。比如gb中小内存的分配。
如果需要在已经分配的内存上面建立一个对象则需要进行placement new,这个只是operator new的另一种实现,这样提高分配速度(new的时候需要在堆中查找可以分配的空间),因为内存之前已经分配好,不需要进行当前内存大小是否符合本次分配。但需要重点注意申请是需要显示调用构造和析构函数,例子如下
class btVoronoiSimplexSolver { }; void* mem = btAlignedAlloc(sizeof(btVoronoiSimplexSolver),16); m_simplexSolver = new (mem)btVoronoiSimplexSolver();
析构的时候需要调用析构函数
m_simplexSolver->~btVoronoiSimplexSolver();
btAlignedFree(m_simplexSolver); //确保不再使用这块内存需要释放,否则内存泄露。
static inline void *btAlignedAllocDefault(size_t size, int alignment) { void *ret; char *real; //sAllocFunc自定义分配方式这里可以认为是malloc real = (char *)sAllocFunc(size + sizeof(void *) + (alignment-1)); if (real) { ret = btAlignPointer(real + sizeof(void *),alignment); *((void **)(ret)-1) = (void *)(real); } else { ret = (void *)(real); } return (ret); }
提前分配缓存的时候最好多分配4个字节,可以用来存放一些额外数据等。