Function allocate_unique

Synopsis

#include <src/entt/core/memory.hpp>

template <typename Type, typename Allocator, typename... Args>
auto allocate_unique(Allocator &allocator, Args &&...args)

Description

Allows std::unique_ptr to use allocators (waiting for C++20).

Template Parameters

Type - Type of object to allocate for and to construct.

Allocator - Type of allocator used to manage memory and elements.

Args - Types of arguments to use to construct the object.

Parameters

allocator - The allocator to use.

args - Parameters to use to construct the object.

Returns
A properly initialized unique pointer with a custom deleter.

Mentioned in

Source

Lines 145-164 in src/entt/core/memory.hpp.

template<typename Type, typename Allocator, typename... Args>
auto allocate_unique(Allocator &allocator, Args &&...args) {
    static_assert(!std::is_array_v<Type>, "Array types are not supported");

    using alloc_traits = typename std::allocator_traits<Allocator>::template rebind_traits<Type>;
    using allocator_type = typename alloc_traits::allocator_type;

    allocator_type alloc{allocator};
    auto ptr = alloc_traits::allocate(alloc, 1u);

    ENTT_TRY {
        alloc_traits::construct(alloc, to_address(ptr), std::forward<Args>(args)...);
    }
    ENTT_CATCH {
        alloc_traits::deallocate(alloc, ptr, 1u);
        ENTT_THROW;
    }

    return std::unique_ptr<Type, allocation_deleter<allocator_type>>{ptr, alloc};
}





Add Discussion

Log in to comment