Effective C++ Ed. 3rd: Item 20. Prefer pass-by-reference-to-const to pass-by-value

  • For User-defined types(yes, for even small ones) Instead of
    Way 1:
    returnType FunctionName(ArgType1 arg1, ...);

    use
    Way 2:
    returnType FunctionName(const ArgType1& arg1, ...);

    This would reduce the cost of calling copy constructor and destructor for each argument passed as shown above.
  • If a derived object of class ArgType1 is passed by Way1, the copy the called function will get will contain only information defined in Base Class ie. ArgType1 here due to Object Slicing. It can be prevented using Way2.

Note: Iterators and function objects of STL and build-in types are better off passed by value due to their design.
prev | next
I hope this helps
Cheers and try hosting at Linode.
Monish

No comments:

Post a Comment