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

后端 未结 6 1314
轻奢々
轻奢々 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:23

    General rule:

    A member function should be const if it both compiles when marked as const and if it would still compile if const were transitive w.r.t pointers.

    Exceptions:

    • Logically const operations; methods that alter internal state but that alteration is not detectable using the class's interface. Splay tree queries for example.
    • Methods where the const/non-const implementations differ only by return type (common with methods the return iterator/const_iterator). Calling the non-const version in the const version via a const_cast is acceptable to avoid repetition.
    • Methods interfacing to 3rd party C++ that isn't const correct, or to code written in a language that doesn't support const

提交回复
热议问题