I’ve got such a C++ code (please don’t ask why it looks so ugly 😉 – you have to believe that because of further part of code it really has a sense):
IntSet temp;
SuperSet superSet;
for (uint i = 0; i < noItems; i++) {
temp.insert(i);
superSet.insert(temp);
temp.clear();
}
It is intended for preparing noItems sets of integers (IntSet, each containing one integer value) and inserting it to other set (SuperSet). Both sets are defined as follows:
typedef unsigned int DataType;
typedef std::set<DataType> IntSet;
typedef std::set<IntSet> SuperSet;
For me, this code shouldn’t work as intended, because just after inserting temp to superSet I’m clearing the temp, and I found that insert is getting a reference as its argument: pair<iterator,bool> insert ( const value_type& x ); (http://www.cplusplus.com/reference/stl/set/insert/)
So, as the result of the code presented above, I should get a SuperSet containing only cleared IntSet‘s. But “unfortunately” this code works – all IntSet‘s are filled with proper values… So my question is – what does insert method from STL’s set really do in its body? Does it simply copy objects that are passed to it by reference? And what is the difference in this method’s behaviour between passing object or primitive types?
Thank you for your answers!
insert()takes a reference argument to avoid the copy when passing the argument. but it creates a copy when stores the item in the collection. This is why theclear()can work in this case. Also, this is true in both cases, so even though you are “reusing”temp, there will be separate copies insuperSet