由于我们的应用程序有着很高的性能和内存限制,我们的编码标准禁止使用默认堆——也就是说,不能使用malloc
或默认的new
。每个内存分配都必须选择几个特定的分配器之一;类似于:
// declared globally
void* operator new( size_t size, CustomAllocHeap* heap, const char* perpetrator_name )
{
return heap->Allocate( size, perpetrator_name );
}
// imagine a bunch of CustomAllocHeap's declared globally or statically, thus
Vector* v = new( gPhysicsHeap, __FUNCTION__ ) Vector( 1.0f, 2.0f, 3.0f, 4.0f );
// or in a class
Thingy* p = new( this->LocalArenaHeap, __FUNCTION__ ) Thingy();
尽管我们在代码中保持了良好的纪律性,但某些标准C++组件(容器、std::function
)暗中调用默认的new
堆是非常糟糕的。如果能以某种方式彻底禁用默认的
new
,那么任何隐式导致默认分配的代码行将立即抛出编译器错误,这将让我们立即注意到这些问题。显然,我们可以使
new
引发运行时错误例如。void* operator new ( size_t ) { __debugbreak(); return NULL; }
但最好在编译时就能收到有关此事的警告。这可行吗?
我们的应用程序是为一个固定平台(x64与Visual Studio)构建的;可移植性无关紧要。
void* operator new ( size_t ) { __debugbreak(); return NULL; }
的作用:它替换了进程使用的默认 new 操作符,只需要链接即可。因此,OP 知道这个机制,并不认为它可以用来解决他的问题。 - cmaster - reinstate monica