Search code examples
c++boost-asioasio

Question about the implementation of std::istream& operator>>(std::istream& is, icmp_header& header)


I saw such an implementation for asio::icmp_header in 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
}

Why not write the method like this:

   friend std::istream& operator>>(std::istream& is, icmp_header& header)
    { return is.read(reinterpret_cast<char*>(header.rep_), sizeof(icmp_header)); }

You see class icmp_header is a simple class without any inheritance.

To avoid the unforeseen\uncertain padding on different operating systems?


Solution

  • It is not the class definition in the header file that defines how large an ICMP header is, but it is the protocol definition. And from there it can be derived that the header is 8 octets (bytes). Therefore, it is reasonable to hard-code the size in the read() function call in order to ensure that exactly that many bytes are read.

    That the size of the buffer in the class definition is also 8 characters, is just because to make it sufficiently large. Theoretically, the implementers could have chosen a larger size for the buffer, but that would not change the fact that the data stream has just 8 bytes dedicated for the header.