c++ - 优化函数内部参数的使用

标签 c++

在一次面试测试中,针对以下代码:

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/

相关文章:

c++ - 基于策略的设计决策

c++ - 打印字节序列

c++ - 递归函数中的 GOTO 指令

C++ 随机数生成,范围为 [0...n],尽可能快速和懒惰?

c++ - Mac 操作系统高塞拉利昂 : OS upgrade fails make in C++

c++ - 如何在 C++ 中打印成员函数地址

c++ - 如何在 Visual Studio 2012 中创建和运行简单的 C++ 程序?

c++ - OpenCV 冲浪 : Cost function between two features?

c++ - 试图用 lambda 找到二维 vector 的最小元素

c++ - 在 C++ 中刷新组合框?