When should a member function have a const qualifier and when shouldn't it?

后端 未结 6 1311
轻奢々
轻奢々 2021-02-06 09:04

About six years ago, a software engineer named Harri Porten wrote this article, asking the question, \"When should a member function have a const qualifier and when shouldn\'t i

6条回答
  •  醉酒成梦
    2021-02-06 09:13

    Here are some good articles:
    Herb Sutter's GotW #6
    Herb Sutter & const for optimizations
    More advice on const correctness
    From Wikipedia

    I use const method qualifiers when the method does not alter the class' data members or its common intent is not to modify the data members. One example involves RAII for a getter method that may have to initialize a data members (such as retrieve from a database). In this example, the method only modifies the data member(s) once during initialization; all other times it is constant.

    I'm allowing the compiler to catch const errors during compile time rather than me catching them during run-time (or a User).

提交回复
热议问题