Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading