要求對象產生於Heap之中
考慮如下代碼:
classHeapClass
{
public:
voidDestory() const {deletethis;}
private:
~HeapClass(){}
};
HeapClass* ptr = newHeapClass;
ptr->Destory();
這樣的調用真是很厲害,想生成非Heap對象都不成了。
對於繼承和組合的情況不想多說了,比較無趣的說。
判斷某個對象是否位於Heap內
考慮如下代碼:
newHeapClass(* newHeapClass);
你覺得編譯器應該怎麼做?
1.調用operator new
2.調用Constructor
3.調用第二個operator new
4.調用第二個Constructor
但是可以讓人足夠驚訝,編譯器對此並不做承諾,所以實際的實現可能是:
1.調用operator new
2.調用第二個operator new
3.調用Constructor
4.調用第二個Constructor
而VC6是這樣實現的。
classHeapClass
{
private:
void* operatornew[](size_tsize);
typedefconstvoid * RawAddress;
voidoperatordelete[](void* ptr);
public:
voidoperatordelete(void *ptr)
{
printf("delete
");
::operatordelete(ptr);
m_address.erase(std::remove(m_address.begin(),m_address.end(),ptr),m_address.end());
return;
}
void* operatornew(size_tsize)
{
printf("new
");
void * ptr = ::operatornew(size);
m_address.push_back(ptr);
returnptr;
}
HeapClass()
{
printf("Constructor!
");
}
HeapClass(constHeapClass&)
{
printf("copy Constructor!
");
}
virtualvoidDestory() const {deletethis;}
virtual ~HeapClass() = 0;
boolisOnHeap() const
{
// const void * rawAddress = dynamic_cast<const void *>(this);
constvoid * rawAddress = (constvoid *)(this);
std::deque<RawAddress>::iteratoriter = std::find(m_address.begin(),m_address.end(),rawAddress);
returniter != m_address.end();
}
private:
staticstd::deque<RawAddress> m_address;
};
HeapClass::~HeapClass(){}
std::deque<HeapClass::RawAddress> HeapClass::m_address;
classDHeapClass:publicHeapClass
{};
我在VC6中寫了這個Demo測試了一下,但是const void * rawAddress = dynamic_cast<const void *>(this);會出現異常,這讓我覺得很郁悶,所以這個Demo只能支持普通的繼承方式,不支持多種繼承和虛擬繼承。
禁止對象產生於heap之中
考慮如下代碼:
classHeapClass
{
private:
void* operatornew(size_tsize);
void* operatornew[](size_tsize);
voidoperatordelete(void *ptr);
voidoperatordelete[](void* ptr);
public:
HeapClass(){printf("Constructor!
");}
HeapClass(constHeapClass&){printf("copy Constructor!
");}
public:
~HeapClass(){}
};
這確實是比較簡單的事情。