C 与 C++ 中的 const 正确性

2022-01-23 00:00:00 c constants c++

我了解 const 正确性的含义,我的问题不是关于 const 正确性是什么.所以我不期待对此的解释或 C++-FAQ 链接.

I understand what const correctness means and my question is not about what const correctness is. So I am not expecting an explanation or C++-FAQ links for that.

我的问题是:

  • C中的const和C++中的const在语义上有什么区别?和
  • 造成差异的原因是什么?
  • What are the semantic differences between const in C and const in C++? and
  • What is the reason for the difference?

如果能引用各自标准中的引述来明确差异,那就太好了.

Quotes from the respective standards which make the differences clear would be nice to have.

我经常在 C 和 C++ 之间切换,我想知道在此过程中应该牢记的要点.

I regularly switch between C and C++ and I would like to know the important points that one should keep in mind while doing so.

我似乎不记得这些的原因(如果你能提供一个推理,特别感谢),但从我的脑海中,我记得:

I don't seem to remember the reason for these (special thanks if you can provide a reasoning) but from the top of my mind, I can remember:

  • C++ 中的 const 变量默认有内部链接,而 C 中它们有默认的外部链接;
  • const 对象在 C++ 中可以用作编译时值,但在 C 中不能用作编译时值;
  • 指向字符串文字的指针在 C++ 中必须是 char const*,但在 C 中可以是 char*.
  • const variables in C++ have internal linkage by default, while in C they have default external linkage;
  • const objects can be used as compile-time values in C++, but cannot be used as compile-time values in C;
  • Pointers to string literals must be an char const* in C++ but in C it can be char*.

我错过了什么?

推荐答案

除了你引用的不同,还有库的不同史蒂夫・杰索普提到,

In addition to the differences you cite, and the library differences that Steve Jessop mentions,

char* p1;
char const* const* p2 = &p1;

在 C++ 中是合法的,但在 C 中不合法.从历史上看,这是因为 C最初允许:

is legal in C++, but not in C. Historically, this is because C originally allowed:

char* p1;
char const** p2 = &p1;

在标准被采用前不久,有人意识到这在 const 安全性中打了一个洞(因为现在可以为 *p2 分配一个char const*,这导致 p1 被分配一个 char const*);和没有实时深入分析问题,C委员会禁止任何除了顶级 const 之外的其他 const.(即 &p1 可以是分配给 char **char **const,但不分配给 char const**也不是 char const* const*.)C++ 委员会做了进一步的分析,意识到问题只存在于 const级别后跟一个非const级别,并计算出必要的措辞.(参见标准中的 §4.4/4.)

Shortly before the standard was adopted, someone realized that this punched a hole in const safety (since *p2 can now be assigned a char const*, which results in p1 being assigned a char const*); with no real time to analyse the problem in depth, the C committee banned any additional const other than top level const. (I.e. &p1 can be assigned to a char ** or a char **const, but not to a char const** nor a char const* const*.) The C++ committee did the further analysis, realized that the problem was only present when a const level was followed by a non-const level, and worked out the necessary wording. (See §4.4/4 in the standard.)

相关文章