为什么需要 select_on_container_copy_construction?

Jos*_*cus 2 c++ memory-management c++11 c++17

对于分配器,为什么select_on_container_copy_construction需要与仅重载复制构造函数相反?

是否存在我们想要定义两个单独的复制构造实现的情况,具体取决于我们是复制实际的分配器还是容器?

Ker*_* SB 5

(您所指的特征实际上称为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.

  • @KerrekSB std::pmr::polymorphic_allocator 使用 select_on_container_copy_construction 在副本上生成具有默认内存资源的 pmr 分配器,而不是传播现有内存资源。 (2认同)