I’m having trouble finding a good answer to this. For some reason I thought STL sort would be implemented using swap for better support of complicated types, but as I ended up digging through the code a bit it appears it is actually doing a binary copy. Can someone confirm this? I guess binary copy would actually be preferred to swap.
Side Question: Are any of the STL algorithms or container operations implemented using swap? (Outside of std::swap obviously.) I want to be aware of when it is prudent to implement my own swap for complicated types.
Edit: Reason I’m asking is if you have something like:
class MyClass {
vector<int> vec_data;
int a;
int b;
}
vector<MyClass> my_vec;
sort(my_vec.begin(), my_vec.end(), MyCustomCompare);
I want to make sure the sort isn’t calling the copy constructor of the vector, which would happen if you called the default Copy constructor of MyData. Hence my question is sort calling swap, copy assign, etc?
It depends on your STL implementation. The GCC STL implementation uses a combination of introsort and insertion sort. It appears that
std::swap(or your specialization) will be invoked in the introsort loop, but it will not be invoked by the insertion sort.If you don’t have a specialization of
std::swap, then the defaultstd::swapimplementation will use a temporary copy to implement swap.It does not use binary copy (except for some POD types, which may have specializations hidden deep within the STL libraries).
Also, in C++0x, it seems likely that the insertion sort will use move semantics (rvalue references).