Search code examples
c++stlfunctor

STL Function Objects on pointer types


I read that "library guarantees that less (and other function objects) on pointer types is well defined". It is from C++ Primer 5th edition. And example is:

vector <string *> nameTable;
sort(nameTable.begin(), nameTable.end(), less<string *>());

But when I try this:

string *p1 = new string("abc");
string *p2 = new string("abc");
cout << equal_to<string *>()(p1, p2);

It returns 0 which means false. Why?

EDIT: Sorry, I read and understand wrong the book. It says:

vector<string *> nameTable;
sort(nameTable.begin(), nameTable.end(), [](string *a, string *b) { return a < b; });    // undefined
sort(nameTable.begin(), nameTable.end(), less<string*>());    // ok. however, meaningless

Solution

  • Your comparison will compare the pointers and not the strings they point to. Comparing pointers using < or > is specified as implementation specific. Using == and != are the only well-defined operations on pointers, but it still only compares the pointers.

    The std::less (as well as std::greater etc.) templates do have well-specified meanings for comparison of pointers (through specializations). But they still compare the pointers and not what they point to.

    The simple solution? Don't use pointers!

    In modern C++ there are few uses of pointers beyond polymorphism. Pointers to strings are even fewer (if any) uses for. The exception might be the smart pointers from C++11, but then I recommend you see them in terms of ownership rather than self-deleting pointers.