Friday, June 20, 2008

Memory Management

Creation of an object can either be on the heap or the stack.
Stack objects are usually created by 
Object i;
whereas heap objects are created by
Object* p = new Object;

The only difference is that the destructor of the object created on the stack is invoked when the object gets out of scope, whereas to invoke the destructor for an object created on the heap we need to explicitly delete the object. 

Restricting Object Creation
I will discuss how we can force creation of an object on a specific location -- that is heap or stack.

Heap Only
To restrict the creation of an object on the heap, that is the object will only be created via new, the destructor should be declared as private.

class Object
{
private:
~Object();
};

The following code will fail to compile.
int main(int argc, char* argv[])
{
Object obj;
};

When the object gets out of scope, the destructor cannot be accessed because it is private.
This will force us to create the object on the heap.

int main(int argc, char* argv[])
{
Object* obj = new Object;
};
Now, the question is how do we delete the object since we cannot access the destructor?
We add a public function in class Object, say destroy().
 
void Object::destroy()
{
delete this;
}
So now we can do,
int main(int argc, char* argv[])
{
Object* obj = new Object;
// do other stuffs here
obj->destroy();
// obj is no longer valid here
};

Stack Only
To restrict the creation of an object on the stack, the trick is to not allow the use of operators new, as well as operator delete for completeness. To do this, we hide new and delete. So the class should look like
class Object
{
private:
void* operator new();
void operator delete();
};
For some advance compiler, the definition of the operators are not required. But for some compilers that do require, we can create an empty definition for the operators. Also, for completeness we should also override and hide the array versions of operators new and delete.

No comments: