Require objects to arise in heap
Consider the following code:
classHeapClass
{
public:
voidDestory() const {deletethis;}
private:
~HeapClass(){}
};
HeapClass* ptr = newHeapClass;
ptr->Destory();
Such a call is really powerful, want to generate a heap object is not.
For the inheritance and combination of the situation do not want to say more, more boring said.
Determine if an object is in heap
Consider the following code:
newHeapClass(* newHeapClass);
What do you think the compiler should do?
1. Call operator NEW
2. Call constructor
3. Call the second operator new
4. Call a second constructor
But it can be surprising enough that the compiler does not commit to this, so the actual implementation might be:
1. Call operator NEW
2. Call the second operator new
3. Call constructor
4. Call a second constructor
And VC6 is the way to achieve it.
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::d eque<rawaddress>::itEratoriter = Std::find (M_address.begin (), M_address.end (), rawaddress);
Returniter!= m_address.end ();
}
Private:
Staticstd::d eque<rawaddress> m_address
};
Heapclass::~heapclass () {}
std::d eque Classdheapclass:publicheapclass
{};
I wrote this demo test in VC6, but the const void * rawaddress = Dynamic_cast<const void *> (this); it makes me feel very depressed, So this demo only supports normal inheritance, and does not support multiple inheritance and virtual inheritance.
Prohibit objects from heap
Consider the following code:
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(){}
};
This is indeed a relatively simple matter.