SlideShare a Scribd company logo
The C++ Core
Guidelines for
Safer Code
Rainer Grimm
Training, Coaching and,
Technology Consulting
www.ModernesCpp.de
Guidelines
Best Practices for the Usage of C++
 Why do we need guidelines?
 C++ is a complex language in a complex domain.
 A new C++ standard is published all three years.
 C++ is used in safety-critical systems.
Reflect your coding habits.
Most Prominent Guidelines
 MISRA C++
 Motor Industry Software Reliability Association
 Based on MISRA C
 Industry standard in automotive, avionic, and medicine domain
 Published 2008 C++03
 AUTOSAR C++14
 Based on C++14
 More and more used in automotive domain (BMW)
 C++ Core Guidelines
 Community driven
Overview
 Philosophy
 Interfaces
 Functions
 Classes and class hierarchies
 Enumerations
 Resource management
 Expressions and statements
 Error handling
 Constants and immutability
 Templates and generic programming
 Concurrency
 The standard library
 Guideline support library
Syntactic Form
 About 350 rules and a few hundred pages
 Each rule follows a similar structure
 The rule itself
 A rule reference number
 Reason(s)
 Example(s)
 Alternative(s)
 Exception(s)
 Enforcement
 See also(s)
 Note(s)
 Discussion
Guidelines Support Library (GSL)
A small library for supporting the guidelines of the C++ core
guidelines.
 Implementations are available for
 Windows, Clang, and GCC
 GSL-lite works with C++98, and C++03
 Components
 Views
 Owner
 Assertions
 Utilities
 Concepts
Interfaces
I.11: Never transfer ownership by a raw pointer (T*)
 func(value)
 func has an independent copy of value and the runtime is the owner
 func(pointer*)
 pointer is borrowed but can be zero
 func is not the owner and must not delete the pointer
 func(reference&)
 reference is borrowed but can’t be zero
 func is not the owner and must not delete the reference
 func(std::unique_ptr)
 std::unique_ptr is the owner of the pointer
 func(std::shared_ptr)
 std::shared_ptr is an additional owner of the pointer
 std::shared_ptr extends the lifetime of the pointer
Interfaces
I.13: Do not pass an array as a single pointer
 What if n is wrong?
 Use span from the GSL
Functions
F.43: Never (directly or indirectly) return a pointer or a
reference to a local object
Classes
C.2: Use class if the class has an invariant; use struct if
the data members can vary independently
 The data members can vary independently
 The data members has an invariant
Classes
C.20: If you can avoid defining any default operations, do
C.21: If you define or =delete any default operation,
define or =delete them all
Sticky Bits - Becoming a Rule of Zero Hero
Enum
Enum.3: Prefer enum classes over “plain” enums
 Can only be accessed in the scope of the enumeration.
 Don't implicitly convert to int.
 Don't pollute the global namespace.
 The default type is int, but you can adjust it.
Resource Management
R.1: Manage resources automatically using resource
handles and RAII (Resource Acquisition Is Initialization)
 RAII-Idiom (Resource Acquisition Is Initialization)
 The lifetime of a resource is bound to an automatic object.
 The resource will be initialized in the constructor of the object;
released in the destructor of the object.
 Used
 Containers of the Standard Template Library and std::string
 Smart pointers
 Locks
 std::jthread (C++20)
Resource Management
Expressions and Statements
ES.28: Use lambdas for complex initialization,
especially of const variables
but widget x should be const
Expressions and Statements
ES.100: Don’t mix signed and unsigned arithmetic
mixed arithmetic with GCC, Clang, and MSVC
Concurrency and Parallelism
CP.8: Don’t try to use volatile for synchronization
 std::atomic
 Atomic (thread-safe) access to shared state.
 volatile
 Access to special memory, for which read and write optimisations
are not allowed.
Java volatile C++ atomic== C++ volatile!=
Concurrency and Parallelism
CP.9: Whenever feasible use tools to validate your
concurrent code
Thread Sanitizer detects data races at runtime.
g++ threadArguments.cpp -fsanitize=thread -g –o threadArguments
skip
Concurrency and Parallelism
Error Handling
E.7: State your preconditions
E.8: State your postconditions
 Precondition: should hold upon entry in a function.
 Postcondition: should hold upon exit from the function
 Assertion: should hold at its point in the computation.
Constants and Immutability
Con.2: By default, make member functions const
The method read should be const!
Constants and Immutability
 Physical constness:
 The object is const and can not be changed.
 Logical constness:
 The object is const but could be changed.
Templates and Generic Programming
 Usage  Definition
T.10: Specify concepts for all template arguments
 Concepts are a compile-time predicate.
Templates and Generic Programming
 Core language concepts
 Same
 DerivedFrom
 ConvertibleTo
 Common
 Integral
 Signed Integral
 Unsigned Integral
 Assignable
 Swappable
 Comparison concepts
 Boolean
 EqualityComparable
 StrictTotallyOrdered
 Object concepts
 Destructible
 Constructible
 DefaultConstructible
 MoveConstructible
 Copy Constructible
 Movable
 Copyable
 Semiregular
 Regular
 Callable concepts
 Callable
 RegularCallable
 Predicate
 Relation
 StrictWeakOrder
Templates and Generic Programming

More Related Content

What's hot

Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3
Randy Scovil
 
Flag Waiving
Flag WaivingFlag Waiving
Flag Waiving
Kevlin Henney
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
Suchit Patel
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
guptkashish
 
C++
C++C++
Lesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbersLesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbers
PVS-Studio
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
Chitrank Dixit
 
Diving into monads in cats library
Diving into monads in cats libraryDiving into monads in cats library
Diving into monads in cats library
Knoldus Inc.
 
Token and operators
Token and operatorsToken and operators
Token and operators
Samsil Arefin
 
12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp
sharvivek
 
Pattern Matching using Computational and Automata Theory
Pattern Matching using Computational and Automata TheoryPattern Matching using Computational and Automata Theory
Pattern Matching using Computational and Automata Theory
IRJET Journal
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
Parametricity
ParametricityParametricity
Parametricity
Shyamendra Solanki
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
tarun308
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
K Durga Prasad
 

What's hot (17)

Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3
 
Flag Waiving
Flag WaivingFlag Waiving
Flag Waiving
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
 
C++
C++C++
C++
 
Lesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbersLesson 9. Pattern 1. Magic numbers
Lesson 9. Pattern 1. Magic numbers
 
Constants and variables in c programming
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
 
Functions
FunctionsFunctions
Functions
 
Diving into monads in cats library
Diving into monads in cats libraryDiving into monads in cats library
Diving into monads in cats library
 
Token and operators
Token and operatorsToken and operators
Token and operators
 
Hd3
Hd3Hd3
Hd3
 
12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp
 
Pattern Matching using Computational and Automata Theory
Pattern Matching using Computational and Automata TheoryPattern Matching using Computational and Automata Theory
Pattern Matching using Computational and Automata Theory
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Parametricity
ParametricityParametricity
Parametricity
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 

Similar to The c++coreguidelinesforsavercode

Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
Sayed Ahmed
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
Sayed Ahmed
 
Modern C++
Modern C++Modern C++
Modern C++
Richard Thomson
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
ppd1961
 
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
Rowank2
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
Vishwa Mohan
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEW
shyamuopten
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
Richard Thomson
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
sachindane
 
Bound and Checked
Bound and CheckedBound and Checked
Bound and Checked
Kevlin Henney
 
C++ language
C++ languageC++ language
C++ language
Hamza Asif
 
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
abdulhaq467432
 
C++ ppt
C++ pptC++ ppt
C++ ppt.pptx
C++ ppt.pptxC++ ppt.pptx
C++ ppt.pptx
Gauravghildiyal6
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
Mihai Todor
 

Similar to The c++coreguidelinesforsavercode (20)

Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Modern C++
Modern C++Modern C++
Modern C++
 
Glimpses of C++0x
Glimpses of C++0xGlimpses of C++0x
Glimpses of C++0x
 
5 introduction-to-c
5 introduction-to-c5 introduction-to-c
5 introduction-to-c
 
Cyclcone a safe dialect of C
Cyclcone a safe dialect of CCyclcone a safe dialect of C
Cyclcone a safe dialect of C
 
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
C –FAQ:
C –FAQ:C –FAQ:
C –FAQ:
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEW
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Bound and Checked
Bound and CheckedBound and Checked
Bound and Checked
 
C++ language
C++ languageC++ language
C++ language
 
02 c++g3 d (1)
02 c++g3 d (1)02 c++g3 d (1)
02 c++g3 d (1)
 
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
7.-Download_CS201-Solved-Subjective-with-Reference-by-Aqib.doc
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
C++ ppt.pptx
C++ ppt.pptxC++ ppt.pptx
C++ ppt.pptx
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 

Recently uploaded

In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 

Recently uploaded (20)

In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 

The c++coreguidelinesforsavercode

  • 1. The C++ Core Guidelines for Safer Code Rainer Grimm Training, Coaching and, Technology Consulting www.ModernesCpp.de
  • 2. Guidelines Best Practices for the Usage of C++  Why do we need guidelines?  C++ is a complex language in a complex domain.  A new C++ standard is published all three years.  C++ is used in safety-critical systems. Reflect your coding habits.
  • 3. Most Prominent Guidelines  MISRA C++  Motor Industry Software Reliability Association  Based on MISRA C  Industry standard in automotive, avionic, and medicine domain  Published 2008 C++03  AUTOSAR C++14  Based on C++14  More and more used in automotive domain (BMW)  C++ Core Guidelines  Community driven
  • 4. Overview  Philosophy  Interfaces  Functions  Classes and class hierarchies  Enumerations  Resource management  Expressions and statements  Error handling  Constants and immutability  Templates and generic programming  Concurrency  The standard library  Guideline support library
  • 5. Syntactic Form  About 350 rules and a few hundred pages  Each rule follows a similar structure  The rule itself  A rule reference number  Reason(s)  Example(s)  Alternative(s)  Exception(s)  Enforcement  See also(s)  Note(s)  Discussion
  • 6. Guidelines Support Library (GSL) A small library for supporting the guidelines of the C++ core guidelines.  Implementations are available for  Windows, Clang, and GCC  GSL-lite works with C++98, and C++03  Components  Views  Owner  Assertions  Utilities  Concepts
  • 7. Interfaces I.11: Never transfer ownership by a raw pointer (T*)  func(value)  func has an independent copy of value and the runtime is the owner  func(pointer*)  pointer is borrowed but can be zero  func is not the owner and must not delete the pointer  func(reference&)  reference is borrowed but can’t be zero  func is not the owner and must not delete the reference  func(std::unique_ptr)  std::unique_ptr is the owner of the pointer  func(std::shared_ptr)  std::shared_ptr is an additional owner of the pointer  std::shared_ptr extends the lifetime of the pointer
  • 8. Interfaces I.13: Do not pass an array as a single pointer  What if n is wrong?  Use span from the GSL
  • 9. Functions F.43: Never (directly or indirectly) return a pointer or a reference to a local object
  • 10. Classes C.2: Use class if the class has an invariant; use struct if the data members can vary independently  The data members can vary independently  The data members has an invariant
  • 11. Classes C.20: If you can avoid defining any default operations, do C.21: If you define or =delete any default operation, define or =delete them all Sticky Bits - Becoming a Rule of Zero Hero
  • 12. Enum Enum.3: Prefer enum classes over “plain” enums  Can only be accessed in the scope of the enumeration.  Don't implicitly convert to int.  Don't pollute the global namespace.  The default type is int, but you can adjust it.
  • 13. Resource Management R.1: Manage resources automatically using resource handles and RAII (Resource Acquisition Is Initialization)  RAII-Idiom (Resource Acquisition Is Initialization)  The lifetime of a resource is bound to an automatic object.  The resource will be initialized in the constructor of the object; released in the destructor of the object.  Used  Containers of the Standard Template Library and std::string  Smart pointers  Locks  std::jthread (C++20)
  • 15. Expressions and Statements ES.28: Use lambdas for complex initialization, especially of const variables but widget x should be const
  • 16. Expressions and Statements ES.100: Don’t mix signed and unsigned arithmetic mixed arithmetic with GCC, Clang, and MSVC
  • 17. Concurrency and Parallelism CP.8: Don’t try to use volatile for synchronization  std::atomic  Atomic (thread-safe) access to shared state.  volatile  Access to special memory, for which read and write optimisations are not allowed. Java volatile C++ atomic== C++ volatile!=
  • 18. Concurrency and Parallelism CP.9: Whenever feasible use tools to validate your concurrent code Thread Sanitizer detects data races at runtime. g++ threadArguments.cpp -fsanitize=thread -g –o threadArguments skip
  • 20. Error Handling E.7: State your preconditions E.8: State your postconditions  Precondition: should hold upon entry in a function.  Postcondition: should hold upon exit from the function  Assertion: should hold at its point in the computation.
  • 21. Constants and Immutability Con.2: By default, make member functions const The method read should be const!
  • 22. Constants and Immutability  Physical constness:  The object is const and can not be changed.  Logical constness:  The object is const but could be changed.
  • 23. Templates and Generic Programming  Usage  Definition T.10: Specify concepts for all template arguments  Concepts are a compile-time predicate.
  • 24. Templates and Generic Programming  Core language concepts  Same  DerivedFrom  ConvertibleTo  Common  Integral  Signed Integral  Unsigned Integral  Assignable  Swappable  Comparison concepts  Boolean  EqualityComparable  StrictTotallyOrdered  Object concepts  Destructible  Constructible  DefaultConstructible  MoveConstructible  Copy Constructible  Movable  Copyable  Semiregular  Regular  Callable concepts  Callable  RegularCallable  Predicate  Relation  StrictWeakOrder
  • 25. Templates and Generic Programming