我在VS2005中編寫了一個小程序來測試C++全局運算符new是否可以被重載。它可以。關於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;
}
在上面,我的運營商新的定義被調用。如果我從代碼中刪除該函數,則會調用C:\ Program Files(x86)\ Microsoft Visual Studio 8 \ VC \ crt \ src \ new.cpp中的新操作符。
一切都很好。然而,在我看來,我的operator new實現並不會在new.cpp中重載new,它會與它衝突並違反one-definition規則。爲什麼編譯器不會抱怨呢?還是標準說是因爲operator new是如此特殊,單義定義規則在這裏不適用?
謝謝。
請注意,您應該始終爲您實施的每個'operator new'實現匹配的'operator delete'。 (我知道這只是爲了表明你的觀點,但我不能讓自己在沒有這個警告的情況下讓它站立起來。) – sbi 2010-04-28 11:45:24
也許你應該編輯問題的標題,我想你想知道替換的各種用法它實際上你想知道爲什麼替換它沒有引發錯誤。 – 2010-04-28 11:45:45