0

I noticed that many string classes in C++ doesn't implement the == operator to compare to strings. What is the reason behind that? As far as I can see, implementing a class for a string is supposed to make the string an entity by itself, rather than a pointer to a set of characters. So we should definitely expect the == operator to be implemented to compare the values of two entities (i.e. strings)!

Rafid
  • 18,991
  • 23
  • 72
  • 108
  • 2
    Can you give an example of any that don't? std::string does for example. – Jeff Foster Jan 28 '11 at 10:02
  • Hmmm... are you sure about std::string?! I just checked the implementation of std::string (MSVC implementation) and it doesn't contain any implementation for `==`. – Rafid Jan 28 '11 at 10:03
  • I thought the main reason for not implementing it is avoid overriding the default behaviour of `==`, which is supposed to compare the very low level of the values, rather than what they represent (i.e. pointer vs. content). – Rafid Jan 28 '11 at 10:04
  • See http://www.sgi.com/tech/stl/basic_string.html. std::string absolutely, definitely implements ==. – Jeff Foster Jan 28 '11 at 10:13
  • the comparison operators for `std::string` are here http://www.cplusplus.com/reference/string/operators/ – Nim Jan 28 '11 at 10:26

3 Answers3

2

std::string is basic_string and it does have operator==, which uses the compare method of char_traits.

You can even put in a specialist traits class of your own to do case-insensitive comparison.

CashCow
  • 30,981
  • 5
  • 61
  • 92
2

Often, when a class doesn't implement operator==, it's because there's a free function outside the class. The advatnage of a free function operator== is that it supports implicit conversions on both sides. This is especially important for strings, because there you often use const char[] literals and want that implicit conversion. E.g.

MyString S("Hello");
if ("hello" == S) { // Can't use MyString::operator== here
  std::cout << S;
}
MSalters
  • 173,980
  • 10
  • 155
  • 350
1

A reason for not implementing operator== for a string class would be if you believe that there are more ways to compare strings: case sensitive/insensitive, ignore accents,... and you provide different compare functions to let the user specify.

It is still a choice and as Jeff Foster already commented: it is implemented in the only real string in C++ (std::string)

stefaanv
  • 14,072
  • 2
  • 31
  • 53
  • That is why it delegates to the traits class to do the compare. You can get case-insensitive compare by using a traits class that compares that way. – CashCow Jan 28 '11 at 10:09
  • @CashCow: any links for that? Anyway, I was showing a design choice when implementing yet another string. – stefaanv Jan 28 '11 at 10:14
  • here on stack overflow http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – CashCow Jan 28 '11 at 10:46