gpt4 book ai didi

c++ - 为什么 C++ 分配器要求不要求 construct() 构造 value_type 的对象?

转载 作者:行者123 更新时间:2023-12-05 02:30:39 25 4
gpt4 key购买 nike

我在阅读时发现这很奇怪 this .它说value_type等于 T ,但是 construct()构造一个 X 类型的对象, 这与 T 无关.
然而,reference page of std::vector只说

An allocator that is used to acquire/release memory and to construct/destroy the elements in that memory. The type must meet the requirements of Allocator. The behavior is undefined (until C++20)The program is ill-formed (since C++20) if Allocator::value_type is not the same as T.

所以我认为这意味着我可以使用任何 Allocator对于 std::vector<T, Allocator>如果Allocator满足 Allocator 和 Allocator::value_type 的要求与 T 相同.
但是如果Allocator::construct()真的构造不是Allocator::value_type ,怎么能std::vector的实现构造了 std::vector 的元素?

编辑:嗯,std::vector的实现可以只使用“placement new”,但这是什么 Allocator::construct()所有关于?如果它不是用于构建STL容器元素等情况,那么它真正意味着在什么情况下使用?

最佳答案

请注意,a.construct(xp, args) 只是可选的。 std::vector 只需要 allocate() 来分配内存,然后它可以使用 placement-new 在该内存中构造对象。如果分配器具有 construct(),则 vector 可以使用它在先前通过 allocate() 获得的内存中创建对象(也是 T 类型) >.

a.allocate:

Allocates storage suitable for an array object of type T[n] and creates the array, but does not construct array elements. May throw exceptions.

并返回指向已分配内存的指针。


I think I don't understand. X can be any type including T. Isn't that mean X can be something that is not T, so vector cannot use construct if the allocator it uses have X which is not equal to T?

没有。该列表是“Given...”并带有项目符号:

  • xp, a dereferenceable pointer to some cv-unqualified object type X

也就是说,你,调用者,选择一些X。然后分配器必须满足 a.construct(xp, args) 构造类型为 X 的对象的要求。 X 实际上是什么,没有指定,因此无论您选择类型为 Xxp,分配器都必须满足该(可选)要求.


作为类比,假设有人写了一些乘法方法,要求是:

Given some x and y of type int:

  • the method returns the result of x*y.

现在,“int 类型的一些 x 和 y”是您选择的,而“该方法返回 x*y 的结果”是该方法的要求必须履行。这不是选择一些 x 和一些 y 并总是返回 42 的方法,因为有值 x==1y==42 产生正确的结果。相反,它意味着对于您选择的任何 x 和任何 y,该方法应填写“该方法返回 x*y 的结果” (为了简单起见,我在这里忽略了溢出)。

关于c++ - 为什么 C++ 分配器要求不要求 construct() 构造 value_type 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71792448/

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