Why is trivially copyable not standard-layout?

E

edA-qa mort-ora-y

I am wondering why C++11 decided to have both trivially copyable and standard layout types as opposed to just having standard layout. My question is motivated by the below code, which works (at least in gcc) but is not standards compliant. I was hoping the standard would clarify such use and make itlegal, but alas it has not.


struct base { /* is a trivial class*/ };
struct derived : public base { /*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) );


The standard ends up saying that though you can memcpy the type to a character buffer, that resulting buffer is 100% opaque and can *only* be used to copy back to the exact same type. The approach shown above, where you wouldcopy via a base class pointer is not supported.

I'm just looking for an understanding as to this decision. Perhaps somebodycan indicate a compiler (non-historic) that would actually fail (not properly copy) with the above code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top