Joseph Franciscus
Joseph Franciscus

Reputation: 371

Why is select_on_container_copy_construction needed?

For allocators why is select_on_container_copy_construction needed opposed to just overloading the copy-constructor?

Are there instances when we want to define two seperate copy-construction implementations depending on if we are copying the actual allocator vs container?

Upvotes: 3

Views: 1303

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477040

(The trait you're referring to is actually called select_on_container_copy_construction.)

The copy constructors of standard library containers are in fact overloaded and provide an allocator-extended version:

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

However, using an overload is not always an option, and generally allocator-aware containers should be usable just as easily and seamlessly as if you weren't aware of the allocator choices. That means that certain decisions, such as how to allocate a copy of a container, may need to be customizable directly via the allocator type, and not via the user's type.

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.

Upvotes: 7

Related Questions