我在VS2005中写了一个小程序测试C++全局operator new是否可以重载。可以。
#include "stdafx.h"
#include "iostream"
#include "iomanip"
#include "string"
#include "new"
using namespace std;
class C {
public:
C() { cout<<"CTOR"<<endl; }
};
void * operator new(size_t size)
{
cout<<"my overload of global plain old new"<<endl;
// try to allocate size bytes
void *p = malloc(size);
return (p);
}
int main() {
C* pc1 = new C;
cin.get();
return 0;
}
上面调用了我定义的operator new。如果我从代码中删除该函数,则会调用 C:\Program Files (x86)\Microsoft Visual Studio 8\VC\crt\src\new.cpp 中的 operator new。
一切都很好。但是,在我看来,我对 operator new 的实现不会在 new.cpp 中重载 new,它会与之冲突并违反单一定义规则。为什么编译器不提示它?还是标准说因为 operator new 非常特殊,所以这里不适用单一定义规则?
谢谢。
最佳答案
是的,global operator new
的特殊之处在于程序可能会为其提供替代实现。
可替换形式是 operator new
和 operator delete
的单个对象和数组形式以及“不抛出”变体。其他形式,如 placement new 是不可替换的。
关于c++ - 在 C++ 全局运算符上 new : why it can be replaced,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728944/