Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact definition of as_bytes function

Tags:

c++

I found this function while reading and I can't find its definition on CPPreference

programming Principles by Bjarne stroustrup

It is used in this way:

ifs.read(as_bytes(x),sizeof(int));`

I understand how readworks but still can you help me with to_bytes standard definition.


1 Answers

The as_bytes function returns the address of the first byte of the argument (so the read call will overwrite the object x). Therefore in C++11 or later one would write that function as follows:

template <class T>
char* as_bytes(T& x) {
    return &reinterpret_cast<char&>(x);
    // or:
    // return reinterpret_cast<char*>(std::addressof(x));
}

The version linked in the comments predates C++11. Presumably the reason why Stroustrup converts first to void* is because reinterpret_cast is not guaranteed to do the right thing in C++03. Note also that the old version will not work correctly for an argument that has an overloaded & operator.

like image 188
Brian Bi Avatar answered Mar 22 '26 12:03

Brian Bi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!