Does std::any_cast call destructor? How the cast works?

  anycast, c++, stdany
#include <iostream>
#include <any>

using namespace std;

class c {
public:
    c() :a{ 0 } { cout << "constructorn"; }
    c(int aa) :a{ aa } { cout << "Constructorn"; }
    ~c() { cout << "destructorn"; }
    int get() { return a; }
private:
    int a;
};

auto main()->int
{
    any a{ 5 };
    cout << any_cast<int>(a) << 'n';
    
    a.emplace<c>(3);
    cout << '!' << any_cast<c>(a).get() << 'n';
    //des
    cout << 'n';
    
    a.emplace<c>(9);
    cout << '!' << any_cast<c>(a).get() << 'n';
    //des
}

destructor called after each any_cast.
and, below code makes run-time error.
I think the cause is any_cast(C)’s work pipeline is might be like
~C() then X(C) ERROR!!C doesn't exist
any_cast really work like that?

I add blow codes and make run-time error.

class X {
public:
    X() :a{ 0 } { cout << "xonstructorn"; }
    X(c& aa) :a{ aa.get() } { cout << "Xonstructorn"; }
    ~X() { cout << "Xdestructorn"; }
    int get() { return a; }
private:
    int a;
};

auto main()->int
{
    any a{ 5 };
    cout << any_cast<int>(a) << 'n';
    
    a.emplace<c>(3);
    cout << '!' << any_cast<X>(a).get() << 'n';
//runtime error after '!'
    cout << 'n';
    
    a.emplace<c>(9);
    cout << '!' << any_cast<X>(a).get() << 'n';
}

Source: Windows Questions C++

LEAVE A COMMENT