M
M
Mercury132013-12-17 15:59:09
C++ / C#
Mercury13, 2013-12-17 15:59:09

C++, reinterpret_cast and const*: how portable is this code?

"Bicycle" associated with a variable length array.

template <class Elem>
struct Buf1d
{
    size_t _size;
    Elem* _ptr;

    operator const Buf1d<const Elem>&() const
        { return reinterpret_cast<Buf1d<const Elem>&>(*this); }
}

As if no problems and two structures, { size_t _size; int*_ptr; } and {size_t size; const int*_ptr; } inside are guaranteed to be the same, because POD's. Am I right or wrong?
PS There are no other fields, there is no virtual, only methods that are not relevant, like operator[], have been removed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2013-12-17
@Mercury13

1. adding const to Buf1d<const Elem> does not turn { size_t _size; int*_ptr; } to { size_t _size; const int*_ptr; }, at best, in { const size_t _size; int*const_ptr; }
2. const T and T according to C++98 3.9.3:1 are represented the same and have the same alignment.
3. const T *p and T *p according to the same standard, 3.9.2:3 also have the same representation and alignment.
Conclusion: you did not get what you expected, but it is correct and portable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question