Search code examples
c++sizepass-by-referencesemanticspass-by-value

Is Size Really A Concern When Deciding Whether To Pass By Reference Or Value?


I came up with the following table:

+-------------------------------------------------+-----------------------+-----------------+
| Should the callee be able to modify the object? | Is it a large object? |    Semantics    |
+-------------------------------------------------+-----------------------+-----------------+
|                      yes                        |         yes           |    reference    |
|                      yes                        |         no            |    reference    |
|                      no                         |         yes           | const reference |
|                      no                         |         no            |      value      |
+-------------------------------------------------+-----------------------+-----------------+

Now I am not really sure what a large object is. Certainly everything bigger than a pointer, so 8 Bytes. But take a struct with one double and you're already at 8 Bytes.

This answer talks about an overhead of making a reference. Since the question was asked more than 11 years ago, I didn't bother asking there for clarification. Maybe someone could go into detail if this is really a concern since creating a reference it certainly faster than creating a copy, no?

I am not asking when to use which semantics. I also know about move. Much more I am interested in:

  1. Does my table make sense?,

  2. Is size of the object really something to consider when deciding on what semantics to chose, since I think you should almost always use ref (AAR (made up and derived from AAA)) except for built-in's maybe? And

  3. What is a large object? Anything larger than 8 Bytes?


Solution

    1. Does my table make sense?,

    Sure.

    1. Is size of the object really something to consider when deciding on what semantics to chose,

    It can be something to consider, yes. It is not the only thing to consider. It only becomes relevant once you've determined that either value or const ref argument more appropriate than other choices, and you want to choose between them. Even then, there are other considerations besides the size. For example, you'd want to avoid copying any non-trivial types.

    1. What is a large object?

    It depends on many things.

    Anything larger than 8 Bytes?

    Not necessarily.

    Here is a rule of thumb: A pointer sized object and anything smaller than that is definitely small. At some point above that, you'll get a large enough object that it becomes cheaper to avoid the copy. That point will depend on how that object is being used.

    To find out which one is faster for a particular function in your particular program, you can measure.