문제

I have the following function:

void IBinary::writeb( std::ostream& out, double x )
{
   out.write( (char*)&(x), sizeof(double) );
}

This takes the address of x and casts it to a pointer of type char*. I do not understand how/why the first argument to write is of type char*, even if I'm writing a double to a file. There are several overloads of the writeb function and all of them cast to a char*.

Wouldn't that be the equivalent of:

double x = 3.14;
char* c;
c = (char*)&(x);    // ah!

My guess is that this works because we are also passing the size of double to ostream::write. On my computer the size of char is 1 byte, but that isn't always going to be true.

Thus, why does the first argument of ostream::write expect a char* no matter what type of variable is being written?

도움이 되었습니까?

해결책

Did you look up the documentation for write?

basic_ostream& write( const char_type* s, std::streamsize count );

The first parameter is const char_type* s, which means for a std::ostream you need to pass a type const char* or char*. write does not accept any other types.

Now, personally I would write (char*)&(x) as reinterpret_cast<char*>(&x), but leaving that aside, first you take the address of the object using the & (the address-of operator). Next you cast it to a char*. Since a char is one byte, it writes one byte of the object at a time the number of characters specified in count. The cast is there so that the object can be passed to write and so it can spit out the binary representation of the object since you are writing one byte at a time. The char* would point to the first byte of the object and write knows how many bytes big the object is based on you passing sizeof(double) as the second argument.

Note that this is a simple form of serialization.

On my computer the size of char is 1 byte, but that isn't always going to be true.

That is incorrect. char is guaranteed to always be one byte.

다른 팁

ostream::write is an unformatted output function. Unformatted in this case means it's blindly writing out whatever bytes you give it. Using a char * is the best (only?) way to do that.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top