C++ const in getter

前端 未结 5 1364
鱼传尺愫
鱼传尺愫 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 23:38

    const method informs compiler that you will not modify class instance on which this method is called:

    class A {
    public:
    bool getReady() const {
        return ready;
    }
    };
    

    so if you try to modify your object inside getReady() then compiler will issue error. Const methods are usefull where you have ie.: const A&, or const A*, then you can call only const methods on such objects.

    as for:

    const bool isReady() {
        return ready;
    }
    

    this const provides actually no real benefit, because bool is copied while isReady() returns. Such const whould make sense if returned type was a const char* or const A&, in such cases const makes your char string or A class instance immutable.

提交回复
热议问题