Toby Allsopp
“Within C++ is a smaller, simpler, safer language struggling to get out.”
—Bjarne Stroustrup
a set of guidelines for using C++ well… to help people to use modern C++ effectively
The C++ Core Guidelines are a collaborative effort led by Bjarne Stroustrup, much like the C++ language itself.
Rules with no enforcement are unmanageable for large code bases.
Each rule has an Enforcement section listing ideas for enforcement. Enforcement might be by code review, by static analysis, by compiler, or by run-time checks.
A “profile” is a set of deterministic and portably enforceable subset rules (i.e., restrictions) that are designed to achieve a specific guarantee.
- Pro.type: Type safety
- Pro.bounds: Bounds safety
- Pro.lifetime: Lifetime safety
The Guidelines are big on "mechanical" enforcement but where are the tools to do this?
As of clang-3.9, only a handful of checks implemented:
$ clang-tidy -checks='-*,cppcoreguidelines-*' -list-checks Enabled checks: cppcoreguidelines-c-copy-assignment-signature cppcoreguidelines-interfaces-global-init cppcoreguidelines-pro-bounds-array-to-pointer-decay cppcoreguidelines-pro-bounds-constant-array-index cppcoreguidelines-pro-bounds-pointer-arithmetic cppcoreguidelines-pro-type-const-cast cppcoreguidelines-pro-type-cstyle-cast cppcoreguidelines-pro-type-member-init cppcoreguidelines-pro-type-reinterpret-cast cppcoreguidelines-pro-type-static-cast-downcast cppcoreguidelines-pro-type-union-access cppcoreguidelines-pro-type-vararg
compile_commands.json
)set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
$ clang-tidy -p build/ -checks='cppcoreguidelines-*' *.cpp
int f(int *a, int i) {
return a[i];
}
int main() {
int a[] = {1, 2, 3};
const int *p = a;
(void) a[f((int*)p, 0)];
}
example-clang.cpp:2:10: warning: do not use pointer arithmetic [cppcoreguidelines-pro-bounds-pointer-arithmetic]
return a[i];
^
example-clang.cpp:7:18: warning: do not implicitly decay an array into a pointer; consider using gsl::array_view or an explicit cast instead [cppcoreguidelines-pro-bounds-array-to-pointer-decay]
const int *p = a;
^
example-clang.cpp:8:10: warning: do not use array subscript when the index is not an integer constant expression; use gsl::at() instead [cppcoreguidelines-pro-bounds-constant-array-index]
(void) a[f((int*)p, 0)];
^
example-clang.cpp:8:14: warning: do not use C-style cast to cast away constness [cppcoreguidelines-pro-type-cstyle-cast]
(void) a[f((int*)p, 0)];
^