9

In an interview test, for the following code :

void GetPosition(dummyClass& a, dummyClass& b) {
    a = GetOrigin();
    b = a + GetAxis().ToForward() * distance;
}

The interviewer wrote the following comment :

If you return value using out argument then don't use the arguments inside the function, the compiler will generally write the variables to memory and read it right back from memory. Use a local stack variable, this allows the compiler to optimize better and only write the data to memory when absolutely needed.

I never heard about the fact that I should avoid using reference parameters inside the function. Is that a common practice when doing C++, or some really specific optimization? And if so, is there some specific documentation that I could read that would cover that case?

Kestemont Max
  • 1,302
  • 2
  • 8
  • 10
  • 2
    If the parameters are of the same type, the compiler must consider that you can have called `GetPosition(x, x);`, so that `a` and `b` is the same object. – Bo Persson Oct 03 '16 at 15:09
  • @BoPersson `__restrict` could come into use here. – Hatted Rooster Oct 03 '16 at 15:12
  • No, there isn't any reason to not use references. References are the same as pointers in http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in With the caveat stated by Bo. However, I suspect there's more to the sample than you're giving which means we can't really answer your question. – UKMonkey Oct 03 '16 at 15:35

1 Answers1

0

He's right but it's very much a micro-optimisation. If the references are to local variables they will be very close in the stack anyway and likely still in the cache, but they could be references to distant heap object.

In fact you should use pointers rather then references for returns, so that caller can instantly see that the value is likely to be written to. And it makes sense to allow null if caller wants to discard the values. So you naturally create two temporaries then at function exit protect the pointer writes with tests for null.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18
  • 2
    Isn't it just as likely to be a micro-pessimization? To unnecessarily use an extra local stack variable. – Chris Drew Oct 03 '16 at 15:49
  • The difference between using references and pointers, is that the pointer to the referent has already been verified by the compiler. When a function receives a pointer, the pointer could point to anywhere. – Thomas Matthews Oct 03 '16 at 16:10
  • Yes, but whilst a reference must refer to an object of the correct type, no compiler can ensure that it refers to the correct object. – Malcolm McLean Oct 03 '16 at 16:57