C++核心准则​CPL.2:如果你必须使用C,使用C和C++的共同子集,并且使用C++编译器编译C代码

时间:2022-07-26
本文章向大家介绍C++核心准则​CPL.2:如果你必须使用C,使用C和C++的共同子集,并且使用C++编译器编译C代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

CPL.2: If you must use C, use the common subset of C and C++, and compile the C code as C++

CPL.2:如果你必须使用C,使用C和C++的共同子集,并且使用C++编译器编译C代码

Reason(原因)

That subset can be compiled with both C and C++ compilers, and when compiled as C++ is better type checked than "pure C."

这样的子集C和C++都可以编译通过,而且作为C++代码编译时获得比“纯C”更好的类型检查。

Example(示例)

int* p1 = malloc(10 * sizeof(int));                      // not C++
int* p2 = static_cast<int*>(malloc(10 * sizeof(int)));   // not C, C-style C++
int* p3 = new int[10];                                   // not C
int* p4 = (int*) malloc(10 * sizeof(int));               // both C and C++
Enforcement(实施建议)
  • Flag if using a build mode that compiles code as C. 标记将代码按照C编译的情况。
    • The C++ compiler will enforce that the code is valid C++ unless you use C extension options. 除非你使用了C扩展选项,C++编译器会强制代码符合C++规范。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cpl2-if-you-must-use-c-use-the-common-subset-of-c-and-c-and-compile-the-c-code-as-c