A survey of tagged union type usage in modern C++ projects
Gábor Spaits, Kristóf Umann, Zoltán Porkoláb · 2024
Insoftware development, there are various problems for which union types are a suitable solution. In $\mathbf{C}$, and in the earlier $\mathrm{C}++$ versions only untagged unions were available. $\mathbf{C}++17$ introduced the standard library class std::variant as a tagged union type. A tagged union keeps track of the type of the last inserted object. Variants are safer, as they offer various compile-time and runtime mechanisms to guard against misuse. However, it is not impossible to make mistakes with them. In this paper, we surveyed seven large, open source projects, that use std::variant. The purpose of the survey was (1) to understand how $\mathrm{C}++$ projects are using tagged unions, (2) what programming errors can be made with them, and (3) in what way the application of static analysis tools could facilitate the creation of safer code. We observed that variants are used for a wide range of tasks, including network communications, giving alternative implementations to classes, or even in a mechanism reminiscent of inheritance. We learned that values are retrieved from variants in almost all various standard-provided manners except for exceptions. Based on our observations we specified and implemented an open source static analysis checker to detect one of the most critical variant-related problems occurring in $\mathrm{C}++$ programs.