📊 Capítulo 18: Baixo Nível & Alinhamento
Especialização em Sistemas com C++
🗺️ Alinhamento de Memória e o Impacto do Padding em Structs
flowchart TD
subgraph DESORGANIZADA ["Struct Sem Otimização (Tamanho Total: 16 bytes!) 🚨"]
U1["char a (1 byte)"]
U2["[ PADDING INÚTIL: 3 bytes ]"]
U3["int b (4 bytes alinhado em múltiplo de 4)"]
U4["char c (1 byte)"]
U5["[ PADDING INÚTIL: 7 bytes ]"]
end
subgraph OTIMIZADA ["Struct Reordenada (Tamanho Total: 8 bytes!) ⚡"]
O1["int b (4 bytes)"]
O2["char a (1 byte)"]
O3["char c (1 byte)"]
O4["[ PADDING MÍNIMO: 2 bytes ]"]
end
DESORGANIZADA -.-> |"Reordenar do maior para o menor membro"| OTIMIZADA
style DESORGANIZADA fill:#ffebee,stroke:#d32f2f,stroke-width:2px
style OTIMIZADA fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
style U2 fill:#ffcdd2,stroke:#e53935,stroke-width:1px
style U5 fill:#ffcdd2,stroke:#e53935,stroke-width:1px
style O4 fill:#c8e6c9,stroke:#2e7d32,stroke-width:1px
🎯 Slide 1: A Biblioteca <bit> do C++20
#include <bit>
uint32_t val = 0b00001000;
int zeros = std::countl_zero(val); // Contagem de zeros à esquerda
bool eh_potencia_2 = std::has_single_bit(val); // True
- Compila diretamente para instruções nativas do processador (como
POPCNTeLZCNTno x86_64)!
🎯 Slide 2: Alinhamento Estrito com alignas e alignof
// Força a struct a ficar perfeitamente alinhada na fronteira de cache de 64 bytes:
struct alignas(64) LinhaCache {
uint64_t dados[8];
};
- Elimina o fenômeno devastador de False Sharing em sistemas concorrentes de alta frequência!
🎯 Slide 3: std::bit_cast (Type Punning Seguro)
- Converte bits brutos entre dois tipos de mesmo tamanho sem incorrer em Undefined Behavior da violação de Strict Aliasing do C clássico!
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim