编译器是否优化了这部分代码(const getter)

Does compiler optimize this part of code (const getter)?

本文关键字:const getter 代码 这部分 是否 优化 编译器      更新时间:2023-10-16

我有以下类定义:

class foo {
  private:
    bool m_active;
  public:
    const bool isActive() const // (btw do I need return type `const bool&` here?)
    {
       return m_active;
    }  
};
  1. 一个类与const getter (foo->isActive())工作速度比foo->m_active(如果它将是公共的)?我试着看看反汇编代码,但没有发现任何有趣的东西。

  2. 我在哪里可以读到const getter和setter ?

  3. 我需要深入了解这些方法的使用地点和原因。

默认情况下,所有成员函数都被视为函数内联。这意味着编译器将优化整个函数调用,并将其替换为对成员的直接访问。

所以答案是肯定的。编译器会优化它