On 21.07.2017 12:25, jacobnavia wrote:
> Hi
> I have to deal with this code:
> 93// given a pointer to w->m_chunk (where w is a CDBStringWrapper)
> return w.
> 94 static CDBStringWrapper* wrapperFromChunk(StringChunk const* c) {
> 95 return (CDBStringWrapper*)((char*)c -
> offsetof(CDBStringWrapper, m_chunk));
> 96 }
>
> I have read about all kinds of warnings workaround and why the work
> around do not work about this.
>
> What would be the replacement of "offsetof" in C++
It's still `offsetof`.
It's limited to POD types.
> P.S. This code compiled OK for around 12 years.
In general, although the compiler may complain, there won't be a problem
with offsets being dynamic unless some virtual base class is involved,
and there won't be a problem with nullpointers dereferenced at compile
time, so if just the compiler optimizes the expression to compile time
constant you can (safely, but not formally) do things like this:
struct Blah
{
int x;
int y;
virtual ~Blah() {}
Blah( int a, int b ): x{a}, y{b} {}
};
#include <stddef.h> // offsetof
#include <stdio.h>
using Byte = unsigned char;
namespace my{
using Size = ptrdiff_t;
auto dummy() -> Blah* { return nullptr; }
auto y_offset()
-> Size
{
return
reinterpret_cast<Byte*>( &(dummy()->y) )
- reinterpret_cast<Byte*>( dummy() );
}
} // namespace my
auto main()
-> int
{
Blah const o{ 111, 222 };
int const* const py = &o.y;
Blah const* const po =
reinterpret_cast<Blah const*>(
reinterpret_cast<Byte const*>( py ) - //offsetof( Blah, y )
my::y_offset()
);
printf( "%d %d\n", po->x, po->y );
}
Cheers &/ hth.,
- Alf