Saturday, June 16, 2007

don't try to return a reference when you must return an object

basically you might be returning reference to a object created locally in the function and that can cause all sorts of undefined behavior.

think if you really get a benefit from returning a reference to an object that you are creating in the function....also you need to worry who will free it. sometimes you mayn't even be able to get to freeing it.( think  w = a*b*c ) and operator  * returns a reference to a  object created on do u get to temp created in a*b and the second temp created in temp*c

returning static objects is also awful....think multi threaded programs, think ( foo(i)*foo(j) == foo(k) * foo(l) )  will always return true ( because both side point to same static object)

static arrays are also a bad choice.

so if your function must return a new object than let that function return a new object, don't use reference or some other trick to try to get some performance benefit.

compilers can do lots of optimization to reduce/eliminate the overhead when it is possible.

so be sane.
things to remember:
never return a pointer or a reference to a local stack object. a reference to a heap allocated object or a pointer or reference to a local static object if there is a change that more than one such subject will be needed.

No comments: