std::variant::~variant(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… NAME πŸ’…

std::variant::~variant β€” yeah bestie, it's literally the destructor of std::variant, and its name is exactly std::variant::~variant 🫢

This page lives in the C++ Standard Libary (that's the manual name, ok, not me β€” I'm just reporting the vibes πŸ’€), section 3.


✨ Synopsis ✨

~variant();            (since C++17)
                       (until C++20)
constexpr ~variant();  (since C++20)

okay so here's the tea πŸ“ β€” if valueless_by_exception() is true, this thing does absolutely nothing. Like, not a single thing. Nada. Otherwise? It destroys the currently contained value. That's the whole job. Iconic, honestly. πŸ‘‘

And the lowkey important part: this destructor is trivial if std::is_trivially_destructible_v<T_i> is true for all T_i in Types.... Yup, all of them. Every single one. No exceptions. ✨


🌸 Example 🌸

// Run this code

#include <variant>
#include <cstdio>

int main()
{
    struct X { ~X() { puts("X::~X();"); } };
    struct Y { ~Y() { puts("Y::~Y();"); } };

    {
        puts("entering block #1");
        std::variant<X,Y> var;
        puts("leaving block #1");
    }

    {
        puts("entering block #2");
        std::variant<X,Y> var{ std::in_place_index_t<1>{} }; // constructs var(Y)
        puts("leaving block #2");
    }
}

πŸ¦‹ Output πŸ¦‹

entering block #1
leaving block #1
X::~X();
entering block #2
leaving block #2
Y::~Y();

see how block #1 leaves before X::~X(); prints? that's the destructor doing its little end-of-scope moment ✨ the whole variant dies at the closing brace, not before. main character timing, honestly πŸ’…


πŸ’€ Defect reports πŸ’€

So the following behavior-changing defect reports got applied retroactively to previously published C++ standards β€” yes, they went back and fixed the past, no cap 😭

  • P2231R1 β€” applied to C++20 β€” as published, "the destructor was not constexpr while non-trivial destructors can be constexpr in C++20"; correct behavior: made constexpr. slay, we love a glow-up 🌈

ngl if you're relying on the pre-C++20 behavior of this destructor not being constexpr, the committee has already come for you πŸ™ˆ

okay that's the whole page, bestie, you ate it πŸŽ€ big kiss from your local standard library β€” sourced from cppreference.com, dated 2024.06.10, filed under std::variant::~variant(3), manual name C++ Standard Libary. go destroy some values responsibly πŸ’œπŸ«Ά

πŸ“¦ where this page comes from