Question

Does this code copy comp by reference or does it copy the whole object everytime?

If there are at some point copies of the whole object, is there another coding way to avoid those copies ?

Comparator comp(3);

set<string, Comparator> s1(comp);
set<string, Comparator> s2(comp);
set<string, Comparator> s3(comp);
set<string, Comparator> s4(comp); 

Cpp reference claims:

The container keeps an internal copy of alloc and comp, which are used to allocate storage and to sort the elements throughout its lifetime.

but the constructor looks like doing a reference copy

explicit set (const key_compare& comp = key_compare(),
              const allocator_type& alloc = allocator_type());

I am new to C++ and I want to be sure about it. I don't know how to check that

Was it helpful?

Solution

The constructor takes in a const reference, but it creates an internal copy of the comparator(using that reference). Each of the sets in your example will have its own copy of comp.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top