C++中要求(或克制)工具发生于heap中
要求工具发生于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(){}
};
这确实是较量简朴的工作。