user5034652
user5034652

Reputation:

Exact definition of as_bytes function

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.

Upvotes: 3

Views: 1597

Answers (1)

Brian Bi
Brian Bi

Reputation: 119239

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.

Upvotes: 1

Related Questions