std::sortswaps elements with the help of std::swapwhich, in turn, uses the copy constructor and assignment operations, ensuring that you get the correct semantics when exchanging values.
qsort swaps elements by simply replacing the base bits of the elements, ignoring any semantics associated with the types you are changing.
Even if you qsortdon’t know the semantics of the types you sort, it still works fine with non-trivial types. If I am not mistaken, it will work with all standard containers, despite the fact that they are not POD types.
I believe that the premise for qsortworking correctly on a type Tis that it Tis / trivially movable /. At the top of my head, the only types that are not trivially movable are those that have internal pointers. For instance:
struct NotTriviallyMovable
{
NotTriviallyMovable() : m_someElement(&m_array[5]) {}
int m_array[10];
int* m_someElement;
};
If you sorted the array NotTriviallyMovable, you m_someElementwill eventually point to the wrong elements.
My question is: what other types of types do not work with qsort?
source
share