Why is const-correctness specific to C++?

后端 未结 14 573
盖世英雄少女心
盖世英雄少女心 2020-12-23 16:42

Disclaimer: I am aware that there are two questions about the usefulness of const-correctness, however, none discussed how const-correctness is necessary in C++ as oppos

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 17:13

    Actually, it's not... not entirely, anyway.

    In other languages, especially functional or hybrid languages, like Haskell, D, Rust, and Scala, you have the concept of mutability: variables can be mutable, or immutable, and are usually immutable by default.

    This lets you (and your compiler/interpreter) reason better about functions: if you know that a function only takes immutable arguments, then you know that function isn't the one that's mutating your variable and causing a bug.

    C and C++ do something similar using const, except that it's a much less firm guarantee: the immutability isn't enforced; a function further down the call stack could cast away the constness, and mutate your data, but that would be a deliberate violation of the API contract. So the intention or best practice is for it to work quite like immutability in other languages.

    All that said, C++ 11 now has an actual mutable keyword, alongside the more limited const keyword.

提交回复
热议问题