【发布时间】:2019-05-06 02:58:56
【问题描述】:
我想创建一个不可复制的分配器(在 C++14 中),它只分配一个 std::vector 可以使用的固定内存块。我想防止分配器(以及向量)可复制,以防止用户意外分配内存。分配器只能与std::vector 或std::string 一起使用。
所以我的分配器有一个像这样的复制构造函数:
static_allocator(const static_allocator<T>&) = delete;
调用时:
std::vector<int, static_allocator<int>> vvv(static_allocator<int>(3));
我收到以下编译错误:
/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>]’
错误似乎来自于stl_vector.h:265 中没有定义右值分配器的构造函数:
/**
* @brief Creates a %vector with no elements.
* @param __a An allocator object.
*/
explicit
vector(const allocator_type& __a) _GLIBCXX_NOEXCEPT
: _Base(__a) { }
虽然更深入的代码实际上支持右值分配器,但没有调用这些分配器,因为右值是由上述构造函数通过引用获取的。
这是 C++14 中缺少的功能还是我缺少某些选项?同样奇怪的是,在构造向量的时候,没有明显的原因复制了分配器。
完整的代码示例可以在这里找到:https://onlinegdb.com/ByqXwQ4k4
【问题讨论】:
标签: c++ c++11 memory-management allocator