C++ const in getter

前端 未结 5 1423
鱼传尺愫
鱼传尺愫 2021-01-30 22:55

I\'m still learning about C++ and I\'m reading everywhere that I have to use const everywhere I can (for speed reason I think).

I\'m usually write my getter

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 23:47

    There is a huge difference between the two ways.

    const bool isReady()
    

    The code above will return a const bool, but it does not guarantee that the object will not change its logic state.

    bool isReady() const
    

    This will return a bool, and it guarantees that the logic state of your object will not change. In this case it is not necessary to write const in front of the return type. It makes no sense to return a const bool because it is a copy anyway. So making it const is useless. The second const is needed for const correctness, which is not used for speed reasons but to make your program more reliable and safe.

提交回复
热议问题