引用代替 getter

Reference in place of getters?

本文关键字:getter 引用      更新时间:2023-10-16

in C++使用引用代替getter是一种不好的做法吗?

例如:

class X
{
    int mP;
 public:
    const int& P;
    X():P(mP){}
}; 

及以后

X xl;
int h = xl.P;

只需考虑重构以使访问线程安全,这种方式不会很好地工作,并且需要在客户端类/函数中进行大量更改。

如果您有类成员,这些成员保证在实例的生存期内不会更改,则只需提供const int P;并在类的构造函数中正确初始化它。

如果该值在类范围内可见,请使用static const int P;

在任何其他情况下,使用公共获取器:

int P() const; // a return type of 'const int &' would be redundant  

第一枪实施:

int X::P() const
{
    return mP;
}

线程安全实现:

class X {
{
    // ...
private:
    // ...
    mutable std::mutex internalDataGuard;
};
int X::P() const
{
    std::lock(internalDataGuard);
    return mP;
}

这些都不好:

class X { public: int x; };
class X {
    private: int m_x;
    public: const int& get() const { return m_x; }
    public: void set(const int& other)  { m_x = other; } 
};
class X {
    private: int m_x;
    public: const int& x() const { return m_x; }
    public: void x(const int& other)  { m_x = other; } 
};
class X {
    private: int m_x;
    public: const int& x() const { return m_x; }
    public: int& x()  { return m_x; }
};

选择一个,这是一个设计决策。

让"const int&x"发布私有成员将起作用:

class X {
    private: int m_x;
    public: const int& x;
    public: X() : m_x(0), x(m_x) {}
    // Take care for copy and assignment
};

成本是更大的内存占用。