Posts

Showing posts from July, 2026

#pragma once的作用

#pragma once 作用: 1. 当一个头文件被多个源文件或其他头文件直接或间接 #include 时,该指令能确保它只被编译一次。 2. 避免宏名冲突:传统的 #ifndef 保护需要为每个文件设计独特的宏名(如 __MY_HEADER_H__), 若不小心在不同文件用了相同的宏名会导致代码失效;而 #pragma once 基于物理文件路径,彻底避免了命名污染和冲突。 3. 书写简洁:只需在头文件最上方写一行即可,无需写 #ifndef、#define 和 #endif 4 与#ifndef的区别: 4.1 标准性:#ifndef 是 C++ 标准支持的传统方法(也称 Include Guard); 而 #pragma once 虽然是非标准指令,但现代绝大多数主流编译器(如 GCC、Clang、MSVC)都提供了完美支持。 4.2 控制粒度:#ifndef 可以防范同一文件内局部的 代码片段 重复,而 #pragma once 只能针对 整个物理文件 。

Strategy Pattern

  Comparison of Modern C++ Approaches Implementation Type Mechanism Resolution Time Memory Overhead Use Case Runtime (Functional) std::function & Lambdas Runtime Small heap allocation (if lambda captures exceed small-buffer optimization) When algorithms must change on the fly during program execution. Compile-time (Static) Templates & Concepts ( requires ) Compile-time Zero runtime overhead (inlines perfectly) High-performance systems where strategies are known at compile time. Example 1: #include <bits/stdc++.h> class SortingStrategy { public: virtual void sort(std::vector<int>& arr) = 0; }; class BubbleSort : public SortingStrategy { public: void sort(std::vector<int>& arr) override { // Implement Bubble Sort algorithm } }; class QuickSort : public SortingStrategy { public: void sort(std::vector<int>& arr) override { // Implement Quick Sort algorithm } }; // Add more sorting algorithms as ne...

Flyweight Pattern

The Flyweight design pattern is a structural pattern designed to minimize memory usage by sharing as much data as possible with other similar objects. It divides an object's data into two categories: intrinsic state(heavy, constant, and shareable data) and extrinsic state (lightweight, unique, context-specific data) #include <iostream> #include <string> #include <string_view> #include <unordered_map> #include <vector> #include <memory> #include <shared_mutex> // 1. INTRINSIC STATE (The Flyweight) // This class contains heavy, immutable data shared across thousands of instances. class TreeModel { public: TreeModel(std::string name, std::string color, std::vector texture_data) : name_(std::move(name)), color_(std::move(color)), texture_bytes_(std::move(texture_data)) { std::cout texture_bytes_; // Simulates heavy mesh/texture data }; // 2. FLYWEIGHT FACTORY // Manages the shared pool of flyweights. It ensures obje...

Design Patterns

Creational: Factory Method (class) Abstract Factory (object) Builder  (object) Prototype  (object) Singleton  (object) Structral: Adapter (class/object) Bridge (object) Composite (object) Decorator  (object) Facade  (object) Flyweight   (object) Proxy  (object) Behavioral: Interpreter (class) Template Method (class) Chain of Responsibility (object) Command (object) Iterator (object) Mediator (object) Memento (object) Observer (object) State (object) Strategy (object) Visitor (object)