Wednesday, July 2, 2008

Restriction on creation of object into heap, stack, static memory

This is just for a kind of information.

Here I am going to explain how to make a class so that user can create object of it on free List( heap memory) or Stack.

Example 1: Object should be created Only On Heap memory.Idea is that make constructor as private so that no one create on stack. But one drawback is that constructor can be overloaded so better make destructor as private member of class because Destructor can'nt be overloaded. It's very safeto make destructor as private member of class for this purpose.
Code: cpp

class HeapOnly
{
public:
void DestroyMe() //This function will call destructor
{
delete this; // Current object will be deleted means destructor
}
private:
~HeapOnly(); // destructor only can be call by member function
};
Now you can test above class.
Client Code:

int main()
{
HeapOnly
HeapOnly * ptr = new HeapOnly; // Object created on heap
ptr->DestroyMe() // Object deallocated
}

Example 2: Object should be created Only On stack memory or static memory. Idea is that just overload the new and delete operator and make it private member and dummy implemetation.

Code: Cpp

class autoOnly
{
public:
autoOnly()
{
;
}
~autoOnly()
{
;
}
private:
void* operator new(size_t)
{
// Dummy Implementation
}
void* operator new[](size_t)
{
// Dummy Implementation
}
void operator delete(void*)
{
// Dummy Implementation
}
void operator delete[](void*)
{
//Dummy Implementation
}
};

Now you can test it .
Client Code:

int main()
{
autoOnly *ptr= new autoOnly; // Error " cannt Access private member
autoOnly obj; // Created on stack
static autoOnly obj1; //Created on static memory
return 0;
}

2 comments:

Anonymous said...

Ni9ce concept Of private destructor.

Anonymous said...

Very cool stuff. i got it very nicley