用C const正确性VS C ++ [英] Const correctness in C vs C++

查看:137
本文介绍了用C const正确性VS C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白const正确性手段,我的问题是不是什么const的正确性。所以,我不期待一个解释或C ++ - 为帮助链接

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 用C常量常量之间的语义差异++?

  • 什么是差异的原因?

  • 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 ++但在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;

不久之前,采用的标准,有人意识到,这
拳打在常量安全性(一个洞,因为 * P2 现在可以分配
字符常量* ,这将导致 P1 被分配了一个字符常量* );同
没有真正的时间来分析在深度问题时,C委员会禁止任何
其他常量不是顶层常量等。 (即&放大器; P1
分配给的char ** 的char **常量,而不是一个字符常量**
也不是字符常量* const的* )的C ++委员会做了进一步
分析,意识到问题只有present当常量
水平以及随后的非 - 常量的水平,并制定了必要的
措辞。 (见§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.)

这篇关于用C const正确性VS C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆