dimanche 25 mars 2018

Why do classes with no user-provide cp/mv ctor and have virtual functions but no virtual bases not have "trival cp/mv ctor"?

According to standard:

A copy/move constructor for class X is trivial if it is not user-provided and if

— class X has no virtual functions (10.3) and no virtual base classes (10.1), and

— the constructor selected to copy/move each direct base class subobject is trivial, and

— for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;

otherwise the copy/move constructor is non-trivial.

I think the standard introduced the concept "trival cp/mv ctor" to infer that you can just copy the classes using std::memcpy instead of calling constructor, and there'll be no undefined behavior.

However, the standard doesn't allow the existance of virtual functions, of which I think is against the spirit of "trival cp/mv ctor". A classes with a vtable pointing to virtual functions can still be copied with std::memcpy and has the right behavior. After all, you can't change the vtable of a class in runtime -- that will break other instances of this class.

So, why can't classes with no user-provide cp/mv ctor and have virtual functions but no virtual bases have "trival cp/mv ctor"?

Aucun commentaire:

Enregistrer un commentaire