# 🌳 C++ Idioms & Concepts — Mastery Notes

## 📌 Overview
This series dives deep into modern C++ idioms to build a solid foundation in writing expressive, efficient, and idiomatic code.

---

## 📂 Copy-on-Write Idiom

### ✅ Intuition
Separate resource ownership from copy semantics. Avoid deep copies until a write is needed.

### 💡 Code Sketch
```cpp
class CowString {
private:
    std::shared_ptr<std::string> data;
public:
    CowString(const std::string& s) : data(std::make_shared<std::string>(s)) {}
    void write(char c) {
        if (!data.unique()) data = std::make_shared<std::string>(*data);
        (*data)[0] = c;
    }
};

📂 Erase-Remove Idiom

✅ Intuition

Use STL's remove with erase to actually eliminate elements from containers.

💡 How remove works

Moves matching elements to the end and returns new logical end.

💡 How erase works

Physically removes them from container.

💡 Code Sketch

v.erase(std::remove(v.begin(), v.end(), 5), v.end());

📂 Non-Copyable / Non-Movable Idiom

✅ Use

Prevent accidental copying/moving of resources.

💡 Techniques

class NonCopyable {
public:
    NonCopyable() = default;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator=(const NonCopyable&) = delete;
};

🔁 Interactions


📂 CRTP (Curiously Recurring Template Pattern)

✅ Intuition

A class inherits from a base class template that takes the derived class as a parameter.

template<typename Derived>
class Base {
public:
    void interface() {
        static_cast<Derived*>(this)->implementation();
    }
};

class Derived : public Base<Derived> {
public:
    void implementation() {
        std::cout << "Derived implementation
";
    }
};

🔍 Use Cases

  1. Static polymorphism
  2. Code reuse without runtime cost
  3. Compile-time type enforcement
  4. Mixins (compose behavior)
  5. Expression templates (for DSLs)
  6. Static interfaces / traits
  7. ID logging/tagging systems

🧠 Deep Concepts


🔁 Virtual Dispatch vs CRTP

✅ Virtual Dispatch

✅ CRTP

🔍 Syntax Comparison

Virtual

class Animal {
public:
    virtual void speak() = 0;
};

class Dog : public Animal {
    void speak() override { std::cout << "Woof!
"; }
};

CRTP

template<typename Derived>
class Animal {
public:
    void speak() { static_cast<Derived*>(this)->speak_impl(); }
};

class Dog : public Animal<Dog> {
public:
    void speak_impl() { std::cout << "Woof!
"; }
};

📌 CRTP Use Cases (Summary)

1. Static Polymorphism

Avoid virtual functions with template-based dispatch.

2. Code Reuse Without Runtime Cost

Encapsulate behavior in template base classes, used by multiple derived classes.

3. Logging/Tagging with ID

Auto-assign unique IDs or tags at compile time.

4. Mixins

Add modular reusable functionality by composing CRTP classes.

5. Expression Templates

Delay evaluation of expressions for performance in math libraries.

6. Compile-time Interface Enforcement

Make sure derived class implements certain methods.

7. Static Interfaces (Concepts Alternative)

Avoid runtime overhead while enforcing structure.


🛠️ Downcasting


🧠 VTable (Virtual Table) — Deep Dive

🔍 Example

class A {
public:
    virtual void foo() { std::cout << "A::foo
"; }
};

class B : public A {
public:
    void foo() override { std::cout << "B::foo
"; }
};

Memory Layout