c++ - 按值返回内联函数

标签 c++ optimization memory inline

我正在实现一些数学类型,我想优化运算符以最大限度地减少创建、销毁和复制的内存量。为了演示,我将向您展示我的四元数实现的一部分。

class Quaternion
{
public:
    double w,x,y,z;

    ...

    Quaternion  operator+(const Quaternion &other) const;
}

我想知道以下两个实现有何不同。我确实有一个 += 实现,它在没有创建内存的地方就地运行,但是一些使用四元数的更高级别的操作使用 + 而不是 += 很有用。

__forceinline Quaternion Quaternion::operator+( const Quaternion &other ) const
{
    return Quaternion(w+other.w,x+other.x,y+other.y,z+other.z);
}

__forceinline Quaternion Quaternion::operator+( const Quaternion &other ) const
{
    Quaternion q(w+other.w,x+other.x,y+other.y,z+other.z);
    return q;
}

我的 c++ 是完全自学的,所以当涉及到一些优化时,我不确定该怎么做,因为我不知道编译器如何处理这些事情。还有这些机制如何转化为非内联实现。

欢迎对我的代码提出任何其他批评。

最佳答案

您的第一个示例允许编译器潜在地使用称为“返回值优化”(RVO) 的东西。

第二个示例允许编译器潜在地使用称为“命名返回值优化”(NRVO) 的东西。这两个优化显然密切相关。

可以在此处找到 Microsoft 实现 NRVO 的一些细节:

请注意,文章指出 NRVO 支持始于 VS 2005 (MSVC 8.0)。它没有具体说明这是否同样适用于 RVO,但我相信 MSVC 在 8.0 版本之前使用了 RVO 优化。

This article about Move Constructors by Andrei Alexandrescu有关于 RVO 如何工作(以及编译器何时以及为什么不使用它)的详细信息。

包括这个位:

you'll be disappointed to hear that each compiler, and often each compiler version, has its own rules for detecting and applying RVO. Some apply RVO only to functions returning unnamed temporaries (the simplest form of RVO). The more sophisticated ones also apply RVO when there's a named result that the function returns (the so-called Named RVO, or NRVO).

In essence, when writing code, you can count on RVO being portably applied to your code depending on how you exactly write the code (under a very fluid definition of "exactly"), the phase of the moon, and the size of your shoes.

这篇文章写于 2003 年,现在编译器应该有很大的改进;希望月相对于编译器可能使用 RVO/NRVO 的时间不那么重要(可能是星期几)。如上所述,MS 似乎直到 2005 年才实现 NRVO。也许那时在微软从事编译器工作的人得到了一双比以前大半号的更舒适的新鞋。

您的示例非常简单,我希望两者都能使用更新的编译器版本生成等效代码。

关于c++ - 按值返回内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1313727/

相关文章:

javascript - jQuery包含多个字符串优化

caching - 'flush to disk' 是什么意思?

c++ - 如何自定义转换模板参数

c++ - 如何从 C++ 流中排除某些#include 指令?

mysql - 这个查询有什么问题? EXPLAIN 对我来说很好

linux - 实时系统中高效的内存调度算法

c - 为什么我的值(value)不会增加?内存踩踏/堆栈故障?

c++ - 这个C++方法可以简化吗?

c++ - 内联函数在链接期间发生冲突?

c++ - 移位语法错误