asio::icmp_header我看到了這樣的實作asio-1.22.1/src/examples/cpp03/icmp/icmp_header.hpp
class icmp_header
{
//omit several functions
friend std::istream& operator>>(std::istream& is, icmp_header& header)
{ return is.read(reinterpret_cast<char*>(header.rep_), 8); }
//omit several functions
private:
unsigned char rep_[8]; //no other member variable, indeed
}
為什么不寫這樣的方法:
friend std::istream& operator>>(std::istream& is, icmp_header& header)
{ return is.read(reinterpret_cast<char*>(header.rep_), sizeof(icmp_header)); }
你看到class icmp_header的是一個沒有任何繼承的簡單類。
為了避免不同作業系統上不可預見的\不確定的填充?
uj5u.com熱心網友回復:
不是頭檔案中的類定義定義了 ICMP 頭的大小,而是協議定義。從那里可以得出標頭是 8 個八位位元組(位元組)。因此,在read()函式呼叫中硬編碼大小以確保讀取的位元組數是合理的。
類定義中緩沖區的大小也是8個字符,只是為了讓它足夠大。從理論上講,實作者可以為緩沖區選擇更大的大小,但這不會改變資料流只有 8 個位元組專用于標頭的事實。
uj5u.com熱心網友回復:
該read呼叫不會寫入header但會寫入其成員header.rep_。成員是一個unsigned char[8];8 個位元組的成員。并且沒有填充header會改變這一點。如果read直接寫入header. 然后布局icmp_header很重要。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493788.html
