Writing good cpp14 by default
11 Dec 2024
https://www.youtube.com/watch?v=hEx5DNLWGgA&list=WL&index=1&ab_channel=CppCon https://www.youtube.com/watch?v=xnqTKD8uD64&list=WL&index=1&ab_channel=CppCon
Guidelines
How can we add guidelines that prevent default usage of grenades in cpp? Theres three main grenades we want to tackle.
- Type safety
- Bound safety
- Lifetime safety
Strong idea of cpp is to have no runtime overhead.
Type safety
Donāt use a memory location of type T, that contains type U.
Basically
- Donāt use static cast downcasts, use dynamic casts.
- Use static cast pretty much otherwise.
Bound safety
Donāt access beyond the bounds of allocation.
Basically
- Use array_view and string_view. Lets you for each, but main benefit is that you can compile time assert on ranges.
- Only index into arrays using constant expressions
for(auto& a: b){}
Lifetime safety
Three things
- Delete every heap object once
- Only once, so you get no corruption
- Donāt reference deleted objects
Lots of previous approaches on this
- Taking runtime overheads of cleanup with GC
- Doing whole program analysis, static analysis.
Basically
- Be clear on if something is owning or pointing.
- Donāt use
new
. Use smart pointers to abstract ownership.make_unique or make_shared
- DONāT pass shared_ptr as function parameters and returns, just use refs.
- Keep in mind the lifetime of temporary objects