Tuesday, April 14, 2009

Why pointers are so very important in C++

Pointer are the life line of any C/C++ programmer. The reason is not just the flexibility, but also the additional speed that a pointer adds to your program. The reason is simple, the constructor of your class is not called. Well its actually safer if you send any class object, since the actual object does not get modified. But then its a safe design and will lead to some penalty in terms of speed. Sometimes, all you care for is speed, then its important to understand what happens while a function is being called.

Well in C++ this is what happens when you call a function

1.  All registers are saved on the stack.

2. Stack is saved, usually by incrementing the stack pointer.

3. Parameters to the function are saved to the new stack.

4. Function execution starts

Well the reverse of thing happens when the function returns.

1. Parameters in the stack are destroyed.

2. Saved stack is retrieved, usually my manipulating the stack pointers.

3. All saved registers are restored.

As you can make from the above actions, there is an additional overhead of calling the constructor and destructor of the parameters. This is definitely not going to happen for free. There is a some penalty which you would take.

Its then upto you to decide what you want. Some safe programming or avoiding the penalty.

No comments: