jeudi 24 juin 2021

how to explain the NEW in std::function::_Reset? [duplicate]

I read std::function code in vs2019 c++17, then there is FUNCTION:

    template <class _Fx>
    void _Reset(_Fx&& _Val) { // store copy of _Val
        if (!_Test_callable(_Val)) { // null member pointer/function pointer/std::function
            return; // already empty
        }

        using _Impl = _Func_impl_no_alloc<decay_t<_Fx>, _Ret, _Types...>;
        if constexpr (_Is_large<_Impl>) {
            // dynamically allocate _Val
            _Set(_Global_new<_Impl>(_STD forward<_Fx>(_Val)));
        } else {
            // store _Val in-situ
            _Set(::new (static_cast<void*>(&_Mystorage)) _Impl(_STD forward<_Fx>(_Val)));
        }
    }

I don't understand the use of the NEW(::new (static_cast<void*>(&_Mystorage)) _Impl(_STD forward<_Fx>(_Val))),how to explain? Other code:

    using _Ptrt = _Func_base<_Ret, _Types...>;    

    union _Storage { // storage for small objects (basic_string is small)
        max_align_t _Dummy1; // for maximum alignment
        char _Dummy2[_Space_size]; // to permit aliasing
        _Ptrt* _Ptrs[_Small_object_num_ptrs]; // _Ptrs[_Small_object_num_ptrs - 1] is reserved
    };

    _Storage _Mystorage;

    template <class _Callable, class _Rx, class... _Types>
    class _Func_impl_no_alloc final : public _Func_base<_Rx, _Types...> {
    public:
        using _Mybase       = _Func_base<_Rx, _Types...>;
        using _Nothrow_move = is_nothrow_move_constructible<_Callable>;

        template <class _Other, enable_if_t<!is_same_v<_Func_impl_no_alloc, decay_t<_Other>>, int> = 0>
        explicit _Func_impl_no_alloc(_Other&& _Val) : _Callee(_STD forward<_Other>(_Val)) {}
    };

THANKS!

Aucun commentaire:

Enregistrer un commentaire