What's wrong with const?

前端 未结 12 2258
無奈伤痛
無奈伤痛 2021-01-31 12:06

What are the known shortfalls of const in C++ and C++0x?

12条回答
  •  无人共我
    2021-01-31 12:45

    What's wrong with const is that many programmers don't seem to be able to understand it completely, and a "half-const-correct" project simply does not work. This is what you need to know:

    1. Foo vs. const Foo (or Foo const)
    2. Foo& vs. const Foo& (or Foo const&)
      • references-to-const bind to all kinds of things, while references-to-non-const don't
    3. Foo* vs. const Foo* (or Foo const*)
      • pointer variables can also be Foo* const and const Foo* const (or Foo const* const)
    4. void Foo::mutator() vs. int Foo::accessor() const
      • but pointer members inside const member functions still point to non-const objects
      • so we can accidentally return non-const data from a const-function
    5. iterator vs. const_iterator
      • iterator variables can also be const iterator and const const_iterator

    Migrating to C++ from a language that has no const concept is quite hard, any many fail to see the point.

提交回复
热议问题