std::sort
swaps elements by using std::swap
, which in turn uses the copy constructor and assignment operators, guaranteeing that you get correct semantics when exchanging the values.
qsort
swaps elements by simply swapping the elements' underlying bits, ignoring any semantics associated with the types you are swapping.
Even though qsort
is ignorant of the semantics of the types you are sorting, it still works remarkably well with non-trivial types. If I'm not mistaken, it will work with all standard containers, despite them not being POD types.
I suppose that the prerequisite for qsort
working correctly on a type T
is that T
is /trivially movable/. Off the top of my head, the only types that are not trivially movable are those that have inner pointers. For example:
struct NotTriviallyMovable
{
NotTriviallyMovable() : m_someElement(&m_array[5]) {}
int m_array[10];
int* m_someElement;
};
If you sorted an array of NotTriviallyMovable
then the m_someElement
s would end up pointing to the wrong elements.
My question is: what other kinds of types do not work with qsort
?
Any type that is not a POD type is not usable with qsort()
. There might be more types that are usable with qsort()
if you consider C++0x, as it changes definition of POD. If you are going to use non-POD types with qsort()
then you are in the land of UBs and daemons will fly out of your nose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With