Do I need to define `operator==` to use my class with standard containers?
I'd like clarification on the C++ standard, specifically where it says (my interpretation) in section 20.1.3 that "for class T and an instance of class T called x, T(x) must be equivalent t开发者_开发技巧o x" for the class to work with standard containers.
I couldn't find a definition of 'equivalent'. Does this mean that I have to define operator==
as a member of my class, so that T(x) == x
returns true?
Equivalent is purposefully vague. (To avoid things like implying operator==
must be defined; it doesn't in a general case.)
However, conceptually two things are equivalent if their data represents the same object. If a class has data that might be different when "copied", then you do need to make an operator==
(and possibly operator<
along with rel_ops
) to make sure that "equivalent" is implemented with respect to that. (Effectively, make sure that the mutable data isn't 'part of the class', so to speak.)
It's usually better not to go such a route, because you end up having to patch lots of things up to make sure it works properly. If something is to be copied, let if be fully copied. This makes much more sense.
This means the class should be copy constructable.
And that the copy constructor creates an object that is equivelent to the original.
If you do not define one the compiler will generate a copy constructor.
If the class does not contain any pointers this should work fine in most situations.
Note: You do not need to define the 'operator ==
'
精彩评论