C++ Logo

std-proposals

Advanced search

Re: [std-proposals] RTTI in current_exception

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 9 Jan 2023 13:38:39 +0000
On Mon, Jan 9, 2023 at 9:37 AM Edward Catmur via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Also https://wg21.link/p0933 from about the same time.


That's an interesting paper by Aaryaman, I particularly like making an
'std::any' out of what was thrown -- however 'std::any' uses dynamic
memory allocation, i.e. 'new' to create the object, and it uses
'delete' in its destructor, so std::any would have to be amended
something like as follows:

#include <functional> // function
#include <typeinfo> // typeid, type_info
#include <exception> // exception_ptr
#include <type_traits> // remove_cvref_t

class any {

    void *p = nullptr;
    std::type_info const *pti = nullptr;
    std::function<void(void)> invoke_delete;

public:

    void Reset(void)
    {
        p = nullptr;
        pti = nullptr;
        if ( invoke_delete ) { invoke_delete(); invoke_delete = nullptr; }
    }

    template<typename T>
    any &operator=(T &&rhs) noexcept(false)
    {
        this->Reset();
        typedef std::remove_cvref_t<T> PureT;
        PureT *const pT = new PureT( std::forward<T>(rhs) );
        this->p = pT;
        this->pti = &typeid(T);
        invoke_delete = [pT](void)->void { delete pT; };
        return *this;
    }

    void assign_from_exception(std::exception_ptr const &pe) noexcept
    {
        this->Reset();
        this->p = &pe->object();
        this->pti = &pe->ti();
        invoke_delete = nullptr; // ======================= This
line is important
    }

    ~any(void)
    {
        Reset(); // Won't delete the object that was thrown
    }
};

Received on 2023-01-09 13:38:51