使用C++ 11,它更好#include
<cassert>
还是<assert.h>
?或者没有区别?
编辑:
我似乎应该在C++程序中包含<xxxx.h>或<cxxxx>吗?认为它归结为污染全局命名空间.这是一个特例,因为assert
是一个宏,没有std::assert
?
How*_*ant 33
除了未定义名称的宏之外,其内容<cassert>
与C标准库头<assert.h>
相同static_assert
.1
喜欢<cassert>
.
不推荐使用所有<xxx.h>
C头文件(包括<assert.h>
):
D.5 C标准库头文件[depr.c.headers]
关于static_assert
来自C 的宏的更新
在D.5 [depr.c.headers]中,C++标准将<xxx.h>
头部称为" C头:
1为了与C标准库兼容,C++标准库提供了表141中所示的C头.
在C++ 14中,规范引用了C99(ISO/IEC 9899:1999).C99没有定义宏static_assert
(在任何标题中).C++ 14 <cassert>
在19.3 [断言]中有这个说法:
2内容与标准C库头相同
<assert.h>
.
C++ 17引用了C11(SO/IEC 9899:2011),它确实定义static_assert
了<assert.h>
,并且<cassert>
在22.3.1 [cassert.syn]中有这个说法:
1
<assert.h>
除了static_assert
未定义名为宏的内容外,其他内容与C标准库头相同.
C++ 14和C++ 17都<assert.h>
只是通过引用它们各自的C规范来定义,也是这样:
另见:ISO C 7.2.
(这是指定的C部分<assert.h>
)
我读了这个问题的方法,techincally <assert.h>
,当用C++编译器17编译,其实也定义了一个名为宏static_assert
.然而,这样做是没有意义的,我无法想象任何实现实际上都很麻烦.
无论如何,我坚持上面的建议:
喜欢
<cassert>
.
这只是C++的做事方式.至少在C++ 98/03/11/14/17中,它避免了依赖于已弃用的功能.谁知道C++ 20会带来什么.但C++ 20肯定不会弃用<cassert>
.
1 22.3.1标题简介[cassert.syn]
看代码:
Using assert.h // Compatible with C language standard
---------------
#include <assert.h>
int main() {
assert(true == true); // Execution continues
assert(true == false); // Execution will abort with false value assert!
return 0;
}
Using cassert // Not compatible with C language standard
--------------
#include <cassert>
int main() {
assert(true == true); // Execution continues
assert(true == false); // Execution will abort with false value assert!
return 0;
}
Run Code Online (Sandbox Code Playgroud)
他们都工作!
在C++ 11中哪一个更好?
C.5.1(C++ 17文档部分)对头文件的
修改[diff.mods.to.headers]
为了与C标准库兼容,C++标准库提供了D.5中枚举的C头,但在C++中不推荐使用它们.
存在针对C头,没有C++头
<stdnoreturn.h>
,和<threads.h>
,也不是C标头本身的C部分++.C++头文件(D.4.1)和(D.4.4)以及它们对应的C头文件不包含C标准库中的任何内容,而只包含C++标准库中的其他头文件.
D.5 C标准库头文件[depr.c.headers] 1.为了与C标准库兼容,C++标准库提供了表141中所示的C头.
无论C++ 11和C++ 17个标准规范注明证件使用<X.h>
与C标准的兼容性遗体,但由于其使用被认为过时.
他们正在审查在C++ 20中使用C库头文件的"不引用".<X.h>
以绿色突出显示.截至目前,C++ 11和C++ 17弃用被称为"弱推荐",并且用于保持" C标准库头(c.headers) " 的"调整" 如下所示:
"基本的C库头是必不可少的兼容性功能,不会很快到任何地方." (来自C++ 20评论文档)
D.5 C标准
库头文件[depr.c.headers]弱推荐:除上述之外,还从C++标准删除相应的C头,就像我们没有相应的
<stdatomic.h>
,<stdnoreturn.h>
或者<threads.h>
,标头.如上所述,但有以下调整:20.5.5.2.1 C标准库头[c.headers]为了与C标准库兼容,C++标准库提供了表141中所示的C头.表141-C头
<assert.h> <inttypes.h> <signal.h> <stdio.h> <wchar.h>
<complex.h> <iso646.h> <stdalign.h> <stdlib.h> <wctype.h>
<ctype.h> <limits.h> <stdarg.h> <string.h>
<errno.h> <locale.h> <stdbool.h> <tgmath.h>
<fenv.h> <math.h> <stddef.h> <time.h>
<float.h> <setjmp.h> <stdint.h> <uchar.h>
Run Code Online (Sandbox Code Playgroud)
标题的
<complex.h>
行为就像它只包含标题一样.标题的<tgmath.h>
行为就像它只包含标题<complex>
和<cmath>
.
Bjarne Stroustrup建议通过尽可能减少不兼容性来最大化C和C++语言之间的互操作性.其他人则争辩说,因为它使事情复杂化.
所以,似乎<X.h>
不会去任何地方.最终,你可以使用两者.就个人而言,我会决定使用哪一个让你的代码向后兼容C代码.
归档时间: |
|
查看次数: |
7096 次 |
最近记录: |