在 setter 函数内调用 getter 与直接访问数据成员
问题很简单:是否有必要在 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 inline
d 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类中的代码始终具有对内部数据成员(以及成员函数)的完全访问权限。所以没有必要。我的想法是,
请注意我不要说什么是“最好的”,只是说事情考虑到
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
note I dont say whats 'best', just things to take into account