Impossible to use virtual keyword on destructor

Viewed 73

Is there any valid and usable case, that will force you not to use the virtual keyword before the destructor.

class Base {
public:
  virtual ~Base() { ... } // `virtual` causes error (not compile time or syntax) or wrong behaviour
  // could contain other fields

};

// some example 
2 Answers

It's possible that making the destructor virtual could convert your class from a non-polymorphic type to a polymorphic type.

Note that a polymorphic type is never trivially copyable. So, for example, you could break any use of std::memcpy by the introduction of a virtual destructor.

In some situations - particularly when interoperating with C - that can wreak havoc, as you can no longer assume that the address of an instance of your class is the same as the address of the first member.

Reference: https://en.cppreference.com/w/cpp/types/is_trivially_copyable

Is there any valid and usable case, that will force you not to use the virtual keyword before the destructor.

Yes. If you ever use std::memcpy or std::memcmp with instances of the class or its members, or rely on a pointer to/from an instance being convertible to the first member of the class,or examine common initial sequence of an inactive union member of the class type.

In general: If you rely on the class being a standard-layout type or trivially copyable, then the destructor (as well as all other member functions) must be non-virtual. Most cases of erroneously assuming standard-layoutness or triviality have undefined behaviour. Those properties can be enforced with type traits and static asserts, so that you get a nice compilation error instead.

Related