Exact definition of as_bytes function

后端 未结 1 652
一生所求
一生所求 2021-01-14 02:26

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

programming Principles by Bjarne stroustrup

相关标签:
1条回答
  • 2021-01-14 02:46

    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.

    0 讨论(0)
提交回复
热议问题