Skip to content

Commit

Permalink
describe why we use no virtual-dtor
Browse files Browse the repository at this point in the history
Building with `-Wnon-virtual-dtor` prints warnings for each
`tinyfsm::Fsm` class:

> warning: 'class Elevator' has virtual functions and accessible
> non-virtual destructor [-Wnon-virtual-dtor]

Adding a virtual destructor would waste resources (at least one vtable
entry). There is no reason to have a one, as the MooreMachine class
(and derived classes) is NOT intended to be deleted through a pointer
to it.

Building `examples/api/moore_machine.cpp` results in:

- without virtual destructor:

    # size -B -d moore_machine
       text    data     bss     dec     hex filename
       3277     768     584    4629    1215 moore_machine

- with virtual destructor in `MooreMachine`

    # size -B -d moore_machine
       text    data     bss     dec     hex filename
       3662     808     600    5070    13ce moore_machine

Ref: #21
  • Loading branch information
digint committed Jun 11, 2022
1 parent 01908ca commit 10749f3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion examples/api/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ CXXFLAGS += -fno-rtti
CXXFLAGS += -Wall -Wextra
CXXFLAGS += -Wctor-dtor-privacy
CXXFLAGS += -Wcast-align -Wpointer-arith -Wredundant-decls
CXXFLAGS += -Wshadow -Wcast-qual -Wcast-align -pedantic
CXXFLAGS += -Wshadow -Wcast-qual -Wcast-align -pedantic -Wnon-virtual-dtor

# Produce debugging information (for use with gdb)
#OPTIMIZER = -Og
Expand Down
4 changes: 4 additions & 0 deletions examples/api/moore_machine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ struct Switch : tinyfsm::MooreMachine<Switch>
{
/* pure virtual reaction (override required in all states) */
virtual void react(Toggle const &) = 0;

// ~Switch() {
// std::cout << "* ~Switch()" << std::endl;
// }
};


Expand Down
11 changes: 11 additions & 0 deletions include/tinyfsm.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,17 @@ namespace tinyfsm
template<typename F>
struct MooreMachine : tinyfsm::Fsm<F>
{
// On the one hand giving an object a virtual destructor means it
// will have a vtable and therefore consume 4 (or 8 on 64 bit
// machines) additional bytes per-object for the vptr.
//
// For a class not intended to delete through a pointer to it,
// there is no reason whatsoever to have a virtual destructor. It
// would not only waste resources, but more importantly it would
// give users a wrong hint.
//
//virtual ~MooreMachine() noexcept = default;

virtual void entry(void) { }; /* entry actions in some states */
void exit(void) { }; /* no exit actions */
};
Expand Down

0 comments on commit 10749f3

Please sign in to comment.