C++ class that mandates const objects

后端 未结 5 2003
盖世英雄少女心
盖世英雄少女心 2021-01-16 05:23

First let me ask a general question:

  • It seems to me that C++ is a language whose point is to provide tons of capabilities, to give the programmer the greatest
5条回答
  •  清酒与你
    2021-01-16 06:04

    The crux of the C++ language's design is that it provides abstraction at very little (often zero) cost. Using classes is no more expensive than providing a struct and related functions in C, but the compiler can enforce restrictions on your code such that the semantic benefits of classes are realised. This is just as true for templates, references, lambdas, copy/move semantics, strings, I/O, etc. You don't pay for what you don't use and, when you do use something, you pay very little.

    Another important design principle of C++ is that it doesn't provide language features that can't just be easily built from other language features or that don't provide a useful form of abstraction for the author. Each language feature is a building block that can be used to make a fully expressive program. This aids flexibility. If the language were to provide the feature you're looking for, it would be reducing that flexibility. If you want the state of your object to be const regardless of how the client wants to use it, you need to make every member of your object const - the members are your object's state. C++ doesn't want to give you absolutely everything; it just gives you the necessary tools to write fully expressive code with minimal cost.

提交回复
热议问题