Reference in place of getters?

后端 未结 2 703
情书的邮戳
情书的邮戳 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: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.

提交回复
热议问题