在 setter 函数内调用 getter 与直接访问数据成员

发布于 2025-01-09 14:52:01 字数 632 浏览 0 评论 0原文

问题很简单:是否有必要在 setter 内部调用 getter 来访问对象的成员变量?假设所有 getter 都是内联的,并返回对成员的 const 引用。

举个例子:

class Foo
{
public:
    inline const std::uint32_t& getValue( ) const noexcept
    {
        return m_value;
    }

    inline const std::uint32_t& getBar( ) const noexcept
    {
        return m_bar;
    }

    void setValue( const std::uint32_t value )
    {
        m_value = value * getBar() * 3; // vs m_value = value * m_bar * 3;
    }

private:
    std::uint32_t m_value;
    std::uint32_t m_bar;
};

哪个更惯用?我认为编译器生成的代码应该没有区别。但就可读性而言,它们有点不同。使用 getter 而不是直接键入例如 m_bar 可能有什么好处?

The question is simple: Is it unnecessary to call getters inside setters to have access to an object's member variables? Suppose that all the getters are inlined and return const references to members.

As an example:

class Foo
{
public:
    inline const std::uint32_t& getValue( ) const noexcept
    {
        return m_value;
    }

    inline const std::uint32_t& getBar( ) const noexcept
    {
        return m_bar;
    }

    void setValue( const std::uint32_t value )
    {
        m_value = value * getBar() * 3; // vs m_value = value * m_bar * 3;
    }

private:
    std::uint32_t m_value;
    std::uint32_t m_bar;
};

Which one is more idiomatic? I think there should be no difference in the generated code by the compiler. But in terms of readability, they're a bit different. What could be the benefits of using getters instead of directly typing e.g. m_bar?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戒ㄋ 2025-01-16 14:52:01

类中的代码始终具有对内部数据成员(以及成员函数)的完全访问权限。所以没有必要。我的想法是,

  • 如果 getter 尤其是 setter 有副作用(想象一下您记录特定值更改的次数或验证值),那么您应该将它们称为
  • 编译发布时的开销消失,因为编译器可以看到您只是在读取或写入值(如果它们是简单的读取和写入 get/set),
  • 您可能会养成总是调用它们的习惯,以防万一您以后希望它们产生副作用,

请注意我不要说什么是“最好的”,只是说事情考虑到

Code in the class always has full acess to the internal data members (and member functions too). So it is not necessary. My thoughts on if you should do it

  • if the getters and particularly setters have side effects (imagine you keep a count of how many times a particular value is changed, or validate a value) then you should call them
  • the overhead when compiled for release will disappear since the compiler can see that you are just reading or writing the value (if they are simple read and write get/set)
  • you might get into the habit of always calling them just in case you later want them to have side effects

note I dont say whats 'best', just things to take into account

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文