Saturday, April 11, 2015

Pass By Pointer in C++


Passing argument to a function can be more efficient when using the pass-by-reference method, especially when the argument size is huge.

int fn(int& x, int& y)

The same level of efficiency can also be achieved using constant pointers.  You can change the value pointed to but not the pointer itself, similar to using references

int fn(int* const p, int* const q)

Similar to returning a reference in a function, be careful not to returning a pointer to an out-of-scope object. Commonly, the return pointer points to an area in heap allocated by the new operator.  Likewise, using a pointer to receive a returning pointer is efficient as it will not involve any copying of the object content.  Using a variable to receive a returning pointer will end up making a copy of the object the pointer points to.

No comments: