mardi 4 décembre 2018

Non-Copyable STL Allocator

I want to create a non-copyable allocator (in C++14) which just allocates a fixed memory block a std::vector can use. I want to prevent the allocator (and therefore also the vector) from being copyable to prevent the user from accidentally allocating memory. The allocator is only intended to be used with a std::vector or maybe std::string.

So my allocator has a copy constructor like this:

static_allocator(const static_allocator<T>&) = delete;

When calling:

std::vector<int, static_allocator<int>> vvv(static_allocator<int>(3));

I get the following compilation error:

/usr/include/c++/5/bits/stl_vector.h: In instantiation of ‘std::_Vector_base<_Tp, _Alloc>::_Vector_impl::_Vector_impl(const _Tp_alloc_type&) [with _Tp = int; _Alloc = static_allocator<int>; std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type = static_allocator<int>]’:
/usr/include/c++/5/bits/stl_vector.h:128:20:   required from ‘std::_Vector_base<_Tp, _Alloc>::_Vector_base(const allocator_type&) [with _Tp = int; _Alloc = static_allocator<int>; std::_Vector_base<_Tp, _Alloc>::allocator_type = static_allocator<int>]’
/usr/include/c++/5/bits/stl_vector.h:265:18:   required from ‘std::vector<_Tp, _Alloc>::vector(const allocator_type&) [with _Tp = int; _Alloc = static_allocator<int>; std::vector<_Tp, _Alloc>::allocator_type = static_allocator<int>]’

The error comes seems to come from the fact that in stl_vector.h:265 there is no constructor for rvalue allocators defined:

/**
*  @brief  Creates a %vector with no elements.
*  @param  __a  An allocator object.
*/
explicit
vector(const allocator_type& __a) _GLIBCXX_NOEXCEPT
: _Base(__a) { }

While the code deeper actually supports rvalue allocators but those are not called because the rvalue is taken by reference by the constructor mentioned above.

Is this a missing feature in C++14 or am I missing some option?

Full code example can be found here: https://onlinegdb.com/ByqXwQ4k4

Aucun commentaire:

Enregistrer un commentaire