Jos*_*cus 2 c++ memory-management c++11 c++17
对于分配器,为什么select_on_container_copy_construction
需要与仅重载复制构造函数相反?
是否存在我们想要定义两个单独的复制构造实现的情况,具体取决于我们是复制实际的分配器还是容器?
(您所指的特征实际上称为select_on_container_copy_construction
。)
标准库容器的拷贝构造函数是实际上超载,并提供分配器扩展版本:
A a1 = f(), a2 = g(); // allocators
std::vector<int, A> v1(a1);
std::vector<int, A> v2(v1, a2); // allocator-extended copy
std::vector<int, A> v3 = v1; // regular copy, uses select_on_container_copy_construction
Run Code Online (Sandbox Code Playgroud)
然而,使用重载并不总是一种选择,通常分配器感知容器应该像您不知道分配器选择一样容易和无缝地使用。这意味着某些决定,例如如何分配容器的副本,可能需要直接通过分配器类型进行定制,而不是通过用户类型进行定制。
For example, you could imagine a situation where the contents of one vector all go onto one (possibly growable) arena, but when you make a new vector, you'd like that to go onto a new, separate arena, and generic code should not need to have to know about this.
Whether this library feature is useful in practice is a separate question, but hopefully this shows why this part design has some motivation.