Use of 'const' for function parameters

前端 未结 30 3294
借酒劲吻你
借酒劲吻你 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:21

    When I coded C++ for a living I consted everything I possibly could. Using const is a great way to help the compiler help you. For instance, const-ing your method return values can save you from typos such as:

    foo() = 42
    

    when you meant:

    foo() == 42
    

    If foo() is defined to return a non-const reference:

    int& foo() { /* ... */ }
    

    The compiler will happily let you assign a value to the anonymous temporary returned by the function call. Making it const:

    const int& foo() { /* ... */ }
    

    Eliminates this possibility.

提交回复
热议问题