Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kinds of types does qsort not work for in C++?

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_someElements would end up pointing to the wrong elements.

My question is: what other kinds of types do not work with qsort?

like image 636
Peter Alexander Avatar asked May 30 '11 10:05

Peter Alexander


1 Answers

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.

like image 187
wilx Avatar answered Oct 28 '22 23:10

wilx