Do I need to define `operator==` to use my class with standard containers?

亡梦爱人 提交于 2019-12-11 07:08:19

问题


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 to 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?


回答1:


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.




回答2:


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 =='



来源:https://stackoverflow.com/questions/3278600/do-i-need-to-define-operator-to-use-my-class-with-standard-containers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!