Skip to content

Move code to C++

Frediano Ziglio requested to merge fziglio/spice:mr_cpp into master

I decided to try to move code to C++. I use the term move instead of port because the base design will be kept. I considered Rust as another option however this would require a proper complete redesign to not end with unmanageable Rust. Also team is not well knowledgeable with Rust.

The history of the branch is very long. It all started with simply forcing a C++ compiler, ignoring all the warning and some minor fix to just compile C code with C++ compiler. Then you started playing with some C++ features like encapsulation and inheritance. In the meantime you discover bugs, design flaws. Not all you can backport, obviously so after a while I started making the branch more serious. The key however was finding a tool, Coccinelle, to help changing the syntax. This helped to move forward quite a lot. Other key is the recent quarantine/don't move trend :-)

Some reasons:

  • we don't use much GObject functionality;
  • current code uses extensively object oriented and inheritance which are supported by C++, removing for instance needs for many casts.
  • use IS-A relationship to reduce useless casts;
  • less verbose, calling method is easier and short, code is made more readable;
  • better automation of resource management (less memory leak, less code);
  • more features like polymorphism, exceptions, lambda;
  • more type safe than C;
  • changing public to private or protected does not require huge code changes or scripts to do (with a tool you would lead with lot of diffs).

Why C++ and not other languages?

  • C++ allows to move code from C to C++ in a much smoother way. I don't call this work "conversion" or "porting" but a "move".
  • C++ has memory management similar to C, mixing for instance Rust and C could lead to writing code that will make Rust less secure but assuming is secure.
  • easy to export C from C++, just use extern "C" in declaration, some headers, no binding needed.
  • easy to import C, just include C headers, maximum use extern "C" in declaration.
  • easier to refactor inserting for instance intermediate classes, code needs much less changes.
  • small footprint, C++ libraries are available as systems and already used by Qemu and other libraries we use.

Status:

  • inheritance, methods, access, smart pointers and some templates are used as feature
  • exceptions are not used (code is not exception safe enough and surely we don't want to throw to C code)
  • RTTI used by one last commit (which is pretty limited, can be manually coded)
  • not much libraries used. Some tricks are used to avoid using C++ libraries
Edited by Frediano Ziglio

Merge request reports

Loading