在一次面试测试中,针对以下代码:
void GetPosition(dummyClass& a, dummyClass& b) {
a = GetOrigin();
b = a + GetAxis().ToForward() * distance;
}
面试官写了以下评论:
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.
我从来没有听说过我应该避免在函数内部使用引用参数。这是做 C++ 时的常见做法,还是一些真正特定的优化?如果是这样,是否有一些我可以阅读的特定文档可以涵盖该案例?
最佳答案
他是对的,但这在很大程度上是一个微观优化。如果引用是对局部变量的引用,它们无论如何都会在堆栈中非常接近并且可能仍在缓存中,但它们可能是对远程堆对象的引用。
事实上,您应该使用指针而不是引用来返回,这样调用者可以立即看到可能要写入的值。如果调用者想要丢弃值,允许 null 是有意义的。因此,您自然会创建两个临时对象,然后在函数退出时使用 null 测试保护指针写入。
关于c++ - 优化函数内部参数的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39834660/