C++ Core Guidelines

Official guidelines from experts

Interview Relevant: Industry standards

C++ Core Guidelines

A collaborative effort led by Bjarne Stroustrup to define modern C++ standards.

Key Principles

  • Interfaces: Make interfaces precise and strongly typed.
  • Resource Management: No manual new/delete. Use specific types like vector for ownership.
  • Concurrency: Use higher-level abstractions, avoid raw threads.

Code Examples

Core guidelines for professional C++ code.

cpp
1// Key guidelines:
2
3// P.1: Express ideas directly in code
4// Bad: x = x + 1;
5// Good: ++x;
6
7// I.11: Never transfer ownership by raw pointer
8void process(unique_ptr<Widget> w);  // Takes ownership
9void process(Widget& w);              // Borrows
10
11// F.16: Prefer T*, T&, or smart pointer for "in" params
12void read(const Widget& w);           // Input
13void modify(Widget& w);               // In-out
14void take(unique_ptr<Widget> w);      // Consume
15
16// C.21: Define or delete all special member functions
17class Rule5 {
18public:
19    Rule5() = default;
20    ~Rule5() = default;
21    Rule5(const Rule5&) = default;
22    Rule5& operator=(const Rule5&) = default;
23    Rule5(Rule5&&) = default;
24    Rule5& operator=(Rule5&&) = default;
25};
26
27// R.1: Manage resources automatically using RAII
28{
29    lock_guard<mutex> lock(mtx);
30    // Protected section
31}  // Automatically unlocked
32
33// ES.20: Always initialize objects
34int count{0};  // Not: int count;
35
36// GSL (Guidelines Support Library)
37// gsl::span, gsl::not_null, gsl::owner<T*>

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In