c++ - 通过引用返回时的返回值优化

标签 c++ reference return-value return-value-optimization return-by-reference

我看了很多关于返回值优化的文章。但是我不确定是否完全理解在以下情况下是否会发生这种情况(地址实际上总是相同的):

#include "stdafx.h"

class Type
{
public:
    Type(int a) { m_a = a; }
private:
    Type(const Type & other) {}
    int m_a;
};

class Base
{
public:
    Base() : instance(42) {}
    virtual Type & GetType()
    {
        printf("Base: Address of instance: %i\n", &instance);
        return instance;
    }

private:
    Type instance;
};

class Derived : public Base
{
public:
    virtual Type & GetType()
    {
        printf("Derived\n");
        return Base::GetType();
    }
};

int main()
{
    printf("Base class\n");
    Base b;
    printf("Main: Address of instance: %i\n", &(b.GetType()));

    printf("\nDerived class\n");
    Derived d;
    printf("Main: Address of instance: %i\n", &(d.GetType()));
}

通过引用返回是否总是确保没有调用复制构造函数?
或者是 RVO发生在这里?

最佳答案

Does returning by reference always ensure no copy constructor is called?

RVO 是一种优化技术。标准不保证。当您按值返回时,大多数编译器将应用 RVO。

virtual Type & GetType()
        ^^^^^^

您在这里通过引用返回,这意味着不需要创建拷贝,因此没有复制构造函数调用的开销,因此没有 RVO 的机会或范围。

the addresses are actually always identical

地址实际上总是相同的,因为它们是同一类成员的地址。

关于c++ - 通过引用返回时的返回值优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14934828/

相关文章:

c++ - 为什么 vector::erase() 不会使对已删除元素的引用无效?

c++ - std::vector 是否有用于引用的复制构造函数?

c# - 使用 Microsoft.PowerShell.Commands 找不到命名空间 'CopyItemCommand'

javascript - JS lambda默认返回值

c++ - 我应该对临时内联变量使用++ 运算符吗?

c++ - std::bind 可变参数模板成员函数和通用引用

javascript - 用 jQuery 动态控制一个旋钮

matlab - 找到连续的非零值

c++ - 在 Visual C++ Windows 窗体应用程序中实现 Bonjour SDK

c++ - 使用编译时已知的类型避免模板冗长和动态多态性