1

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

Issam T.
  • 1,677
  • 1
  • 14
  • 32
  • 1
    It takes a `const key_compare&` so that you can pass a temporary. You can also [try it out](http://coliru.stacked-crooked.com/a/4a160601c43a4a6c) and see that size of comparator does make a difference. – jrok Apr 08 '14 at 15:51
  • Thanks again. It seems I need to pay you today for all that amount of answers :) – Issam T. Apr 08 '14 at 16:03

1 Answers1

3

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • Thanks +1. I understand now. But is there another coding way to avoid those copies ? – Issam T. Apr 08 '14 at 15:52
  • @IssamT. not in the set interface. Maybe you can make your comparators share data somehow? – Ivaylo Strandjev Apr 08 '14 at 15:56
  • 1
    Well, I don't know if [this](http://coliru.stacked-crooked.com/a/78cf37b49a2d46ec) is legal, but it works :) – jrok Apr 08 '14 at 15:58
  • @jrok hah interesting idea :) I just wonder if copies are still created. Maybe one should benchmark the memory usage? – Ivaylo Strandjev Apr 08 '14 at 16:01
  • Well yes, I am afraid I can t do better than a pointer inside the comparator toward a structure that holds the parameters that I don t want to copy everytime. but that's add a level of complexity and makes the code not so intuitive – Issam T. Apr 08 '14 at 16:01
  • @jrok yep it seems your idea is nice. – Issam T. Apr 08 '14 at 16:07
  • @IssamT. I'm not so sure, it's more of a hack. You can post a question whether it's legal, if you want. – jrok Apr 08 '14 at 16:08
  • @jrok btw it is definitely dangerous especially if you return the set from a function and the comparator goes out of scope. – Ivaylo Strandjev Apr 08 '14 at 16:11
  • done a new question :) http://stackoverflow.com/questions/22942686/is-this-legal-to-avoid-set-from-creating-actual-copies-of-comparator-object – Issam T. Apr 08 '14 at 16:18