std::variant::~variant(3)
π 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 notconstexprwhile non-trivial destructors can beconstexprin C++20"; correct behavior: madeconstexpr. 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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms