Is there any compiler where the layout requirements for standard layout types do not also apply to trivially copyable types? In particular, the critical rule being that a pointer to the type is a pointer to its first member (where a base class would be considered coming prior to the derived class). That is, the address of the type would be the same address as its base type.
In code, is there any common compiler where the following would not actually work. It seems like common practice to me, thus I was surprised it wasn't standardized in C++11.
struct base { int a; /* is a trivial class*/ };
struct derived : public base { int b; /*still a trivial class*/ }
void copy( base * a, base * b, size_t len )
{
memcpy( a, b, len );
}
...
derived d1, d2;
copy( &d1, &d2, sizeof(derived) );
I know for sure this works in GCC, and I believe it works in MSVC (though I may be wrong). In which non-historic compiler would the above not work as intended?
Extended Example
The above example shows the fundamental problem, but may not show the intent that would get one there. Here is a slightly more verbose example. Essentially anybody can call "send" which will queue up the message, then later something will dispatch each message by casting back to its real type.
struct header { int len, id; }
struct derived : public header { int other, fields; }
void send( header * msg )
{
char * buffer = get_suitably_aligned_buffer( msg->len );
memcpy( buffer, msg, msg->len );
}
void dispatch( char * buffer )
{
header * msg = static_cast<header*>(buffer);
if( msg->id == derived_id )
handle_derived( static_cast<derived*>(msg) );
}
derived d;
d.len = sizeof(d);
d.id = deirved_id;
send( &d );
...
char * buffer = get_the_buffer_again();
dispatch( buffer );
It's still omitting many aspects, but the key parts are shown.