17

Gurus everywhere tell us to const everything unless we need to modify it, yet the standard makes everything mutable until we declare it const.

Am I missing something here, or is this a contradiction? Why aren't C++ types const by default when, according to the experts (some of whom presumably designed the standard), they should be made const by default?

4

3 回答 3

17

各地的大师都告诉我们要 const 一切,除非我们需要修改它,

这是一两年来的传统智慧,是的。

然而,在我们将其声明为 const 之前,该标准使一切都是可变的。

该标准是从大约 50 年前开发的语言发展而来的,当时 const 正确性,甚至类型检查,在很大程度上被认为仅具有学术兴趣。

我在这里遗漏了什么,或者这是一个矛盾?

这并不矛盾;只是一种不起作用的语言,有些人会说它应该起作用。您仍然可以(并且应该)const在适当的情况下声明内容,我们只需要忍受一种不会促使我们采取安全做法的语言。

const为什么默认情况下不是 C++ 类型?

因为更改语言的这样一个基本方面将破坏几乎所有现有代码。这比稍微减少错误的范围要大得多。

于 2013-10-20T14:11:47.990 回答
15

Gurus everywhere tell us to const everything unless we need to modify it,

This makes sense to me. Immutability is a very noble idea.

Rust is a new language (developed by Mozilla) in which variables, by default, are immutable. If you want your variables to be mutable, then you've to make it mutable explicitly by using the keyword mut which is exactly opposite of what C++ does — in C++, you've to make things immutable explicitly by using the keyword const, otherwise they're mutable by default.

Especially with the advent of multicore processors and more multi-threading software than ever before, it makes more sense to me. I think by default there should be more restriction and the restriction should be lifted (when you need to) consciously and explicitly (as opposed to implicitly). For example, members of a class are private by default; the inheritance is private by default. You make them public or protected explicitly. So should be the case with the-right-to-modify a variable. You should not have right to modify a variable, by default (in my opinion). It requires a bit of maturity to appreciate immutability/restriction — by putting restriction, you avoid a whole class of bugs in your software. That is my thought, in support of the statement.

Now coming back to the actual question,

Why aren't C++ types const by default when, according to the const-people they should be made const by default?

It is because

  • Not many programmers realized that immutability (as the default) makes their life easy, as it is a sort of new trend, at least it is catching up very recently.
  • backward-compatibility. C has mutable types by default.
于 2013-10-20T13:47:10.733 回答
1

几年前我也有同样的问题,我写了一些辅助函数来使 const 变量的使用更简洁。

你可以在这里看到它: https ://github.com/pthom/cpp_terse_const

还有我在 stackechange 上关于 codereview 的帖子: https ://codereview.stackexchange.com/questions/106074/const-by-default

请注意,这只是一个练习,我不会在生产中使用它。

于 2017-08-26T18:50:23.750 回答