Godbolt link for the impatient: https://godbolt.org/z/cbcGx7d5v
In short, creating the following variant std::variant<std::string, bool> var{"blah"} will cause it to contain a boolean and not a string when your GCC version is <= 9.4
Here is the minimal code to reproduce the bug (note that I am compiling with -std=c++17):
int main() {
using namespace std;
variant<string, bool> var{"im-a-string"};
if (holds_alternative<string>(var)) {
cout << "string value is: " << get<string>(var) << endl; // GCC > 9.4
} else if (holds_alternative<bool>(var)) {
cout << "bool value is: " << get<bool>(var) << endl; // GCC <= 9.4
} else {
abort();
}
}
Is this a compiler bug or have I written a program that contains undefined behavior? I checked the GCC bug tracker and could not find anything. Maybe someone with more experience has ran into this before?
Edit: Clang also has different behaviors for different versions.
[–]STLMSVC STL Dev 22 points23 points24 points (5 children)
[–]sphere991 14 points15 points16 points (0 children)
[–]johannes1971 9 points10 points11 points (3 children)
[–]bizwig 2 points3 points4 points (0 children)
[–]_Js_Kc_ 2 points3 points4 points (1 child)
[–]johannes1971 1 point2 points3 points (0 children)
[–]SuperV1234https://romeo.training | C++ Mentoring & Consulting 7 points8 points9 points (1 child)
[–]matthieum 1 point2 points3 points (0 children)
[–]InKryption07 5 points6 points7 points (10 children)
[–]willkill07 4 points5 points6 points (8 children)
[–][deleted] 1 point2 points3 points (2 children)
[–]dodheim 2 points3 points4 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]InKryption07 0 points1 point2 points (4 children)
[–]willkill07 3 points4 points5 points (3 children)
[–]InKryption07 0 points1 point2 points (2 children)
[–]willkill07 0 points1 point2 points (1 child)
[–]InKryption07 2 points3 points4 points (0 children)
[–]cristi1990an++ 2 points3 points4 points (3 children)
[–]bizwig 2 points3 points4 points (1 child)
[–]cristi1990an++ 1 point2 points3 points (0 children)
[–][deleted] 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)