Does it make sense to provide non-const reference getter

前端 未结 9 921
滥情空心
滥情空心 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:15

    yes, it makes sense - for maintainability, validation, and consistency.

    you may need to change many aspects of the class in the future, providing an accessor can help minimize breakage of client code.

    you can enter all the validation logic you need here, to ensure that engine is a valid pointer, is not in an unusable state, etc.

    finally, your code will be consistent: you won't have to open the header to know the member visibility - you just always know. this is also useful with templates.

提交回复
热议问题