Use of 'const' for function parameters

前端 未结 30 2812
借酒劲吻你
借酒劲吻你 2020-11-22 03:06

How far do you go with const? Do you just make functions const when necessary or do you go the whole hog and use it everywhere? For example, imag

30条回答
  •  孤街浪徒
    2020-11-22 03:32

    const is pointless when the argument is passed by value since you will not be modifying the caller's object.

    const should be preferred when passing by reference, unless the purpose of the function is to modify the passed value.

    Finally, a function which does not modify current object (this) can, and probably should be declared const. An example is below:

    int SomeClass::GetValue() const {return m_internalValue;}
    

    This is a promise to not modify the object to which this call is applied. In other words, you can call:

    const SomeClass* pSomeClass;
    pSomeClass->GetValue();
    

    If the function was not const, this would result in a compiler warning.

提交回复
热议问题