Reference in place of getters?

后端 未结 2 702
情书的邮戳
情书的邮戳 2021-01-27 04:00

in C++ is it a bad practice to use reference in place of getters?

for example:

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


        
相关标签:
2条回答
  • 2021-01-27 04:42

    Just think about refactoring to make the access thread safe, that won't work well this way and require a lot of changes in the client classes/functions.

    If you have class members, that are guaranteed not to be changed over lifetime of the instance, you can simply provide const int P; and initialize it properly in your class' constructors.

    If the value is to be visible class wide use a static const int P;

    In any other case use a public getter:

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

    1st shot implementation:

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

    Thread safe implementation:

    class X {
    {
        // ...
    private:
        // ...
        mutable std::mutex internalDataGuard;
    };
    
    int X::P() const
    {
        std::lock(internalDataGuard);
        return mP;
    }
    
    0 讨论(0)
  • 2021-01-27 04:49

    None of this is good:

    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; }
    };
    

    Pick one, it's a design decision.

    Having 'const int& x' to publish the private member will work:

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

    The cost is a larger memory footprint.

    0 讨论(0)
提交回复
热议问题