std::codecvt::~codecvt(3)

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

πŸ’… std::codecvt::~codecvt πŸ’…

okay so this is a page from the C++ Standard Library manual, bestie β€” we're in std::codecvt territory and today's main character is the destructor. yes, the destructor. she's lowkey iconic and highkey protected, and you're gonna understand her by the end of this, i promise 🫢


🌸 NAME 🌸

std::codecvt::~codecvt β€” literally just std::codecvt::~codecvt, that's the whole name, no notes πŸ’…


✨ Synopsis ✨

so first things first, she lives here:

Defined in header <locale>

and her signature is giving "you can't touch this":

protected: ~codecvt();

what she does: destructs a std::codecvt facet. that's the job. she destroys it. periodt πŸ’€

but here's the tea, and it's important tea: this destructor is protected and virtual (virtual because of the base class destructor being virtual β€” she inherited that energy, no cap). so an object of type std::codecvt, like most facets, can only be destroyed in exactly two situations:

  • when the last std::locale object that implements this facet goes out of scope πŸ¦‹
  • or if a user-defined class is derived from std::codecvt and implements a public destructor ✨

that's it, those are the two paths. no shortcuts, no sneaky delete, she's protected for a reason πŸŽ€


🧚 Example 🧚

here's the demo, and honestly the comment in the code says it all. run this code:

// Run this code

#include <iostream>
#include <locale>

struct Destructible_codecvt : public std::codecvt<wchar_t, char,
std::mbstate_t>
{
    Destructible_codecvt(std::size_t refs = 0) : codecvt(refs) {}
    // note: the implicit destructor is public
};

int main()
{
    Destructible_codecvt dc;
    // std::codecvt<wchar_t> c; // compile error: protected destructor
}

see what she did there? πŸ‘€ Destructible_codecvt derives from std::codecvt<wchar_t, char, std::mbstate_t>, gives itself a constructor with std::size_t refs = 0, and because the implicit destructor is public, the object dc actually gets to be destroyed. slay πŸ’–

and then the commented-out line? // std::codecvt<wchar_t> c; // compile error: protected destructor β€” that's the vibe check failing fr fr. you can't just make a bare std::codecvt and expect to destroy it, because that destructor is protected. compile error, no cap 😭

bestie warning: don't try to fight the protected destructor. she's protected and virtual, that's not a bug, that's the design. derive your own class with a public destructor if you need to destroy things, iykyk πŸ’…

so yeah, that's the whole page β€” short, sweet, and extremely protected 🌈⭐

source: http://cppreference.com β€” version 2024.06.10 β€” page std::codecvt::~codecvt(3) πŸŽ€ bye bestie, go derive responsibly πŸ’œ

πŸ“¦ where this page comes from