Search code examples
c++typesbuilt-in-types

Passsing primitives by value


I'm reading Scott Meyrses C++ and now an the section about passing-reference-to-const. He said that for user-defined types it's almost always good to pass it by references-to-const, unlike for built-in types.

My question is why the built-in types should be passed by value. Why is it more efficient? I think, that they could be put into registers, but is that the only reason?


Solution

  • When you pass a reference, behind the scenes it's passing a pointer. This is more efficient than passing the whole structure, which could be very large.

    Primitive types are all about the same size as a pointer (at worst they might be twice as big). Some are even smaller -- a char is 1 byte, while pointers are typically 4 or 8 bytes. So there's no efficiency gained by passing by reference instead of passing the value itself.