- Prefer
std::stringover C-style strings to avoid manual memory management and buffer overflows. - Always validate input size and type when using standard input/output streams.
-
Smart Pointers:
- Use
std::unique_ptrfor ownership semantics andstd::shared_ptrfor shared ownership. - Avoid raw pointers wherever possible.
- Use
-
Containers:
- Use
std::vectorinstead of dynamic arrays for automatic memory management. - Prefer
std::mapandstd::unordered_mapfor associative data storage.
- Use
- Use exception handling (
try-catch) for robust error management. - Always catch exceptions by reference:
try { // code } catch (const std::exception& e) { std::cerr << e.what() << std::endl; }
This document highlights the best practices for developing maintainable and high-quality C++ code. It is derived from the 101 rules and guidelines provided in C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter and Andrei Alexandrescu.
- Don’t sweat the small stuff. (Know what not to standardize.)
- Compile cleanly at high warning levels.
- Use an automated build system.
- Use a version control system.
- Invest in code reviews.
- Give one entity one cohesive responsibility.
- Correctness, simplicity, and clarity come first.
- Know when and how to code for scalability.
- Don’t optimize prematurely.
- Don’t pessimize prematurely.
- Minimize global and shared data.
- Hide information.
- Know when and how to code for concurrency.
- Ensure resources are owned by objects. Use explicit RAII and smart pointers.
- Prefer compile- and link-time errors to runtime errors.
- Use
constproactively. - Avoid macros.
- Avoid magic numbers.
- Declare variables as locally as possible.
- Always initialize variables.
- Avoid long functions. Avoid deep nesting.
- Avoid initialization dependencies across compilation units.
- Minimize definitional dependencies. Avoid cyclic dependencies.
- Make header files self-sufficient.
- Always write internal
#includeguards. Never write external#includeguards.
- Take parameters appropriately by value, (smart) pointer, or reference.
- Preserve natural semantics for overloaded operators.
- Prefer the canonical forms of arithmetic and assignment operators.
- Prefer the canonical form of
++and--. Prefer calling the prefix forms. - Consider overloading to avoid implicit type conversions.
- Avoid overloading
&&,||,,(comma). - Don’t write code that depends on the order of evaluation of function arguments.
- Be clear about the kind of class you’re writing.
- Prefer minimal classes to monolithic classes.
- Prefer composition to inheritance.
- Avoid inheriting from classes that were not designed to be base classes.
- Prefer providing abstract interfaces.
- Public inheritance is substitutability. Inherit, not to reuse, but to be reused.
- Practice safe overriding.
- Consider making virtual functions nonpublic, and public functions nonvirtual.
- Avoid providing implicit conversions.
- Make data members private, except in behaviorless aggregates (C-style structs).
- Don’t give away your internals.
- Use the Pimpl idiom judiciously.
- Prefer writing nonmember nonfriend functions.
- Always provide
newanddeletetogether. - If you provide any class-specific
new, provide all of the standard forms (plain, in-place, andnothrow).
- Define and initialize member variables in the same order.
- Prefer initialization to assignment in constructors.
- Avoid calling virtual functions in constructors and destructors.
- Make base class destructors public and virtual, or protected and nonvirtual.
- Destructors, deallocation, and
swapnever fail. - Copy and destroy consistently.
- Explicitly enable or disable copying.
- Avoid slicing. Consider
Cloneinstead of copying in base classes. - Prefer the canonical form of assignment.
- Whenever it makes sense, provide a no-fail
swap(and provide it correctly).
- Keep a type and its nonmember function interface in the same namespace.
- Keep types and functions in separate namespaces unless they’re specifically intended to work together.
- Don’t write namespace
usingin a header file or before an#include. - Avoid allocating and deallocating memory in different modules.
- Don’t define entities with linkage in a header file.
- Don’t allow exceptions to propagate across module boundaries.
- Use sufficiently portable types in a module’s interface.
- Blend static and dynamic polymorphism judiciously.
- Customize intentionally and explicitly.
- Don’t specialize function templates.
- Don’t write unintentionally nongeneric code.
- Assert liberally to document internal assumptions and invariants.
- Establish a rational error-handling policy, and follow it strictly.
- Distinguish between errors and non-errors.
- Design and write error-safe code.
- Prefer to use exceptions to report errors.
- Throw by value, catch by reference.
- Report, handle, and translate errors appropriately.
- Avoid exception specifications.
- Use
vectorby default. Otherwise, choose an appropriate container. - Use
vectorandstringinstead of arrays. - Use
vector(andstring::c_str) to exchange data with non-C++ APIs. - Store only values and smart pointers in containers.
- Prefer
push_backto other ways of expanding a sequence. - Prefer range operations to single-element operations.
- Use the accepted idioms to really shrink capacity and really erase elements.
- Use a checked STL implementation.
- Prefer algorithm calls to handwritten loops.
- Use the right STL search algorithm.
- Use the right STL sort algorithm.
- Make predicates pure functions.
- Prefer function objects over functions as algorithm and comparer arguments.
- Write function objects correctly.
- Avoid type switching; prefer polymorphism.
- Rely on types, not on representations.
- Avoid using
reinterpret_cast. - Avoid using
static_caston pointers. - Avoid casting away
const. - Don’t use C-style casts.
- Don’t
memcpyormemcmpnon-PODs. - Don’t use unions to reinterpret representation.
- Don’t use varargs (
ellipsis). - Don’t use invalid objects. Don’t use unsafe functions.
- Don’t treat arrays polymorphically.
This document outlines comprehensive best practices derived from the MISRA C++:2023 guidelines for using C++17 in safety-critical and security-critical systems. These guidelines are intended to enhance reliability, maintainability, and robustness in software design and implementation.
- Adopt MISRA C++ as a subset of the C++17 standard.
- Avoid reliance on undefined, unspecified, implementation-defined, and conditionally supported behavior.
- Use static analysis tools to detect violations and enforce compliance.
- Avoid constructs that introduce safety risks, such as uninitialized variables, unchecked operations, or invalid memory access.
- Adhere to the principle of least privilege in all code design decisions.
- Follow a consistent style guide for variable naming, indentation, and layout.
- Modularize code into small, well-defined functions with single responsibilities.
Rule 0.0.1: Functions shall not contain unreachable statements.
- Rationale: Unreachable code often indicates a logical error and makes maintenance harder.
- Compliant Example:
int calculate(int value) { if (value > 0) { return value * 2; } return 0; }
- Non-compliant Example:
int calculate(int value) { return 0; value++; // Unreachable code }
Guideline: Minimize dependency on compiler-specific behavior for better portability and maintainability.
- Best Practice:
- Document all assumptions about compiler behavior explicitly.
- Use portable libraries and abstractions where possible.
Rule 0.2.1: Variables with limited visibility should be used at least once.
- Rationale: Unused declarations add noise to the code and may lead to confusion or maintenance errors.
- Example:
namespace { int value = 42; // Non-compliant if unused } void process(int a) { [[maybe_unused]] bool flag = (a > 0); // Compliant with attribute assert(flag); }
Rule 0.1.1: A value should not be unnecessarily written to a local object.
- Rationale: Writing to variables without observing their values wastes resources and might indicate logic errors.
- Example:
int process() { int temp = 0; // Non-compliant if temp is not used return 0; }
Directive 0.3.1: Use floating-point operations carefully to avoid precision loss or overflow.
- Validate inputs and handle special cases such as NaN and infinity explicitly.
- Example:
float compute(float value) { if (std::isnan(value)) { throw std::invalid_argument("NaN encountered"); } return value * 2.0f; }
Rule 4.18: Exceptions should not introduce runtime instability or obscure program flow.
- Compliant Example:
try { performOperation(); } catch (const SpecificError& e) { handleError(e); } catch (...) { logGeneralError(); }
- Non-compliant Example:
try { performOperation(); } catch (...) { // Catch-all with no logging or handling }
Rule 6.7.4: Avoid implicit conversions that might lead to data loss or undefined behavior.
- Compliant Example:
float value = 42.0f; int result = static_cast<int>(value); // Explicit cast
- Non-compliant Example:
float value = 42.0f; int result = value; // Implicit cast
- Encapsulate resource management using constructors and destructors to ensure deterministic cleanup.
- Example:
class ResourceHandler { public: ResourceHandler() { acquireResource(); } ~ResourceHandler() { releaseResource(); } };
Rule 4.12.1: Synchronize shared resources to avoid data races.
- Compliant Example:
std::mutex mutex; void safeIncrement(int& counter) { std::lock_guard<std::mutex> lock(mutex); ++counter; }
- Provide meaningful comments for complex logic, exceptions, and assumptions.
- Avoid redundant comments that merely restate the code.
- MISRA C++: 2023 Guidelines.
- ISO/IEC 14882:2017 (C++17 Standard).
- Industry standards such as IEC 61508, ISO 26262.
This document is a living guideline, intended to evolve with project needs and updates to coding standards. All team members should follow these practices and contribute suggestions for improvement.
This document is comprehensive and includes key examples, rationales, and rules based on the MISRA guidelines. It can be further expanded or customized to align with project-specific coding conventions.