Phần 1
1. Goal
Learn how C++ groups related data using structures and why object size may be larger than the sum of its fields.
After this lesson, you should understand:
1. What a struct is.
2. How struct objects are stored.
3. What padding is.
4. Why alignment exists.
5. How field ordering affects memory usage.Phần 2
2. What Problem Does This Solve?
Real-world data usually contains multiple fields.
Examples:
order
trade
quote
positionA struct groups related information into a single object.
Phần 3
3. Minimum Syntax
Define a structure:
struct Trade
{
int price;
int quantity;
char side;
};Create an object:
Trade trade;Access fields:
trade.price
trade.quantity
trade.sidePhần 4
4. Memory Model
A struct is stored as a single contiguous object.
Fields appear in declaration order.
However, compilers may insert extra bytes between fields.
These bytes are called:
paddingPhần 5
5. Padding
Padding is inserted to satisfy alignment requirements.
Benefits:
faster memory access
better CPU efficiencyImportant:
sizeof(struct)
is not necessarily equal to
sum(sizeof(fields))Phần 6
6. Common Mistakes
6.1 Assuming No Padding
Struct size may be larger than expected.
Always verify with:
sizeof(...)6.2 Poor Field Ordering
Bad field ordering may waste memory.
Placing larger fields first often reduces padding.
6.3 Comparing Raw Memory
Padding bytes may contain unspecified values.
Raw memory comparison can be unreliable.
Phần 7
7. Notes for Trading Code
Trading systems process millions of messages.
Common structures:
Trade
Quote
Order
MarketDataEventMemory layout directly affects:
cache efficiency
latency
throughputUnderstanding padding is important for high-performance systems.
Phần 8
8. End-of-Day Checklist
You should be able to answer:
1. What is a struct?
2. Why use a struct instead of separate variables?
3. What is padding?
4. Why does padding exist?
5. Why can sizeof(struct) be larger than expected?
6. How can field order affect memory usage?Phần 9
9. Conclusion
Structs combine multiple fields into a single object.
The key idea:
Memory layout matters.Padding exists to improve alignment and CPU performance.
Understanding struct layout is a fundamental skill for systems programming and low-latency software.
Mã mẫu hoàn chỉnh
cpp98_foundation/struct & padding/main.cpp
#include <iostream>
struct Trade
{
int price;
int quantity;
char side;
};
int main()
{
Trade trade;
trade.price = 100;
trade.quantity = 50;
trade.side = 'B';
std::cout << "Price: "
<< trade.price
<< '\n';
std::cout << "Sizeof Trade: "
<< sizeof(Trade)
<< '\n';
return 0;
}Tự kiểm tra · không chấm điểm
Bạn đã hiểu những điểm nào?
Đã tự kiểm tra 0/6 mục