我在VS2005中编写了一个小程序来测试C++全局运算符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;
}
Run Code Online (Sandbox Code Playgroud)
在上面,我调用了operator new的定义.如果我从代码中删除该函数,则调用C:\ Program Files(x86)\ Microsoft Visual Studio 8\VC\crt\src \new.cpp中的operator new.
一切都很好.但是,在我看来,我对operator new的实现不会使new.cpp中的new重载,它会与它发生冲突并违反单一定义规则.为什么编译器不抱怨呢?或者说标准是否因为operator new非常特殊,单定义规则在这里不适用?
谢谢.
c++ ×1