arsdever
arsdever

Reputation: 1262

Impossible to use virtual keyword on destructor

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 

Upvotes: 3

Views: 77

Answers (2)

eerorika
eerorika

Reputation: 238311

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.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234665

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

Upvotes: 6

Related Questions