Home > Blogs > 30 C++ Tips in 30 Days: Tip # 18 is it efficient to pass lightweight objects by value?

30 C++ Tips in 30 Days: Tip # 18 is it efficient to pass lightweight objects by value?

By  Dec 6, 2007

Topics: Programming, C/C++

One of the common newbies' errors is returning objects by value. Although there are some rare cases in which returning objects by value is intentional and unavoidable, in the majority of cases it's simply the result of unawareness and lack of understanding.

As a rule, anything that isn’t a built-in type should be returned by reference. The only exception to the rule is iterators, although as we're speaking, iterators are becoming bulkier (Checked STL implementations for example use fat iterators) and therefore should be considered as objects rather than pointers.

Some people think that if an object occupies a tiny bit of memory, say 4 bytes, returning such an object by value is as efficient as returning int by value. This isn't the case. Agreed, lightweight objects do not contain data members and therefore don't occupy much memory. However, their initialization can be quite complex, for example, when the object has virtual functions or base classes. Therefore, don't rely only on sizeof(obj) to decide if the object can be passed by value efficiently. If its initialization isn't trivial, you should return and pass such objects by reference, too. 

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.