Thursday, May 22, 2008

C++ : Little Sugar

In C++ when ever you see a function that accepts a const reference than its a valid candidate for temporaries . Temporaries are objects that are created and destroyed whenever there is mismatch in function arguments and a constructor exists that takes the passed argument and converts it to a destination entity via the constructor .

C++ : Little Sugar

mutable keyword is useful in C++ , when you are changing a member variable in side a constant function . A simple way to remove constantness of the "this" pointer is to use code like this

const_cast(this)

C++ : new operator and operator new

The new operator in C++ is something that cannot be changed . For example
when you use code something like this ,

string *ps = new string("Memory Management");

the new operator is used . Its sole purpose is to allocate memory and initialize it.

The new operator in turn uses the operator new to allocate memory which can be overloaded.

its prototype looks like this :

void * operator new(size_t size);

there is another version of new operator called the placement new , that is used to create objects in pre initialized memory. example usage for it looks like this :

string *ps = new(memory) string("Memory Management");

same is the case for delete operator and operator delete

operator new[] is another type of operator that can be used to allocate new arrays

Tuesday, May 20, 2008

C++ : Little Sugar

While creating objects in C++ , in order to initialize objects use the member initialization list. When initialization of a class starts , initialization of its members happens . If the member initialization list is not used the default constructor of all the class members is called even before entering the constructor . Once inside the constructor the copy constructor or operator = is called to initialize the member objects .

On the other hand if member initialization list is used only the copy constructor is called once and hence you prevent the over head of an extra call.

Monday, May 19, 2008

C++ : Creating Objects

Here are 2 simple rules to allocating and deleting objects.

MyObject * myPointer;

while updating object memory always use code like this:

MyObject::update(){
delete myPointer;
myPointer = NULL;
myPointer = MyObject::CreateNew();
}

while deallocating always use code like this:

MyObject::~MyObject(){
delete myPointer;
myPointer = NULL;
}