gpt4 book ai didi

c++ - 不可复制的 STL 分配器

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:44 26 4
gpt4 key购买 nike

我想创建一个不可复制的分配器(在 C++14 中),它只分配一个 std::vector 可以使用的固定内存块。我想防止分配器(以及 vector )被复制,以防止用户意外分配内存。分配器仅用于 std::vectorstd::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 中缺少的功能还是我缺少某些选项?同样奇怪的是,在构造 vector 时无缘无故地复制了分配器。

完整的代码示例可以在这里找到:https://onlinegdb.com/ByqXwQ4k4

最佳答案

根据requirements for an Allocator type您的分配器类型需要满足 CopyConstructible这意味着你不能删除你的拷贝:

A a1(a)
A a1 = a

Copy-constructs a1 such that a1 == a. Does not throw exceptions. (Note: every Allocator also satisfies CopyConstructible)

关于c++ - 不可复制的 STL 分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53617084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com