2

In the new "C++ Programming Language" book(and probably in previous versions), Bjarne Stroustrup recommends:

  1. Use pass-by-value for small objects
  2. Use pass-by-const-reference to pass large values that you don't need to modify.
  3. ...

Is there a common accepted definition for small objects when it comes to arguments passing? For example it's obvious that any object smaller than the address size is a small object, but what about the objects that have 2, 3, 4 times the size of an address? Are they considered small and should be passed by value?

As a sample code to work on:

struct Vector {float x, y, z;};

Should I prefer:

void do_something_with_vector(Vector v){...}

or:

void do_something_with_vector(const Vector& v){...}
Mircea Ispas
  • 20,260
  • 32
  • 123
  • 211
  • 1
    Possible duplicate: http://stackoverflow.com/q/25273958/596781 – Kerrek SB Aug 19 '14 at 10:38
  • I think "small object" is an object which size less or equial than reference (creating a reference to it does not make sense) –  Aug 19 '14 at 10:38
  • Seems to have 2 duplicates.. – CashCow Aug 19 '14 at 10:41
  • The true answer is far more subtle. It may sometimes be faster to pass your Vector by value, as it will make it easier for the compiler to put its members in registers inside the function, as it knows they cannot change. My personal suggestion is to pass by const reference, and come back to this if you have a performance problem. – Neil Kirk Aug 19 '14 at 10:44
  • @YuriS.Cherkasov I'm pretty sure that that's not the answer. On many architectures, a `double` will be larger than a reference, but it is almost always preferable to pass a single `double` by value. – James Kanze Aug 19 '14 at 10:46
  • 2
    How did this get marked as a duplicate. The question is totally unrelated to the question cited as above. – James Kanze Aug 19 '14 at 10:57
  • @James Of course that statement is applicable to classes, not basic types –  Aug 19 '14 at 12:23
  • @Justin: I added it as another option! – Kerrek SB Jul 09 '19 at 22:29

1 Answers1

1

Small objects are anything the size of or smaller than a pointer. If you pass something larger, like the Vector struct in your example, then it will be copied and that's just a waste :-)

Russ Freeman
  • 1,480
  • 1
  • 8
  • 6