Does it make sense to provide non-const reference getter

前端 未结 9 864
滥情空心
滥情空心 2020-12-16 23:58

Sometimes I need to expose some of the class members. For example in the following example class Mechanic may need direct access to Engine componen

相关标签:
9条回答
  • 2020-12-17 00:20

    They can be useful when the value you are returning is actually on the heap.

    template<class T> class Singleton
    {
    private:
        static T* m_pSingleton;
    
    public:
        T& getSingleton() { assert(m_pSingleton); return(*m_pSingleton); };
    
    }; // eo class Singleton
    
    0 讨论(0)
  • 2020-12-17 00:25

    In this case you would rather need a Car.fix(const Mechanic&) function which then gives the engine to the Mechanic, say: Engine.fix(const Mechanic&), as I suppose the state of the Engine will be modified.

    The original idea of using classes was to tie together the data with its accessor functions. If you do setter or getter which merely returns an internal data, it means that your data is not tied together with its accessor functionality: your class is not complete.

    You want only to expose new data which a class emits. Say Car.get_exhaust() and the Car does not have the exhaust, only produces it, when you ask so. ;)

    Or Fire Riefle.fire() whereas no access for Riefle::Trigger will be fixed by the mechanic like so: Trigger.fix_by(Mechanic) and then the fix_by will call say Mechanic.add_working_hour(0.5). XD

    0 讨论(0)
  • 2020-12-17 00:26

    Instead of thinking about exposing private members of a class think more along the lines of calling methods on those classes. I read an interesting Java article, Why Getter and Setter Methods are Evil, which applies just as much to C++ as it does to Java.

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