I am creating a custom RTTI system for my event system. Below is the EventTypeInfo
class. As you can see, it is noncopyable, just as std::type_info
.
class EventTypeInfo
{
public:
EventTypeInfo(const EventTypeInfo&) = delete;
EventTypeInfo& operator=(const EventTypeInfo&) = delete;
inline bool operator==(const EventTypeInfo& other) const {
return this == &other;
}
};
The way I create these objects for every event class boils down to this:
template<class EventClass>
const EventTypeInfo& event::type::info()
{
static EventTypeInfo typeinfo;
return typeinfo;
}
Given that (1) these objects are created statically (which means they will last for the entire duration of the application), (2) they are noncopyable, and (3) there's no way to modify an EventTypeInfo
's fields without resorting to const_cast
, is it enough for me to implement operator==
is terms of this == &other
, or did I miss something?
If you are sure that there will ever only be one instance of each type, the address compare will be ok.
It is not enough for std::type_info as its uniqueness is not guaranteed by the standard.
In case of a multi-modular application, I think each module might end up with its own copies of static type-info objects. Therefore just comparing an address might be not enough if your events can fly between modules.
As far as I know, RTTI system in GCC had this sort of problem in past, and it caused troubles. Eventually, GCC developers admitted it and fixed to use string comparison in GCC 4.5.
So I would suggest you to do pointer comparison first, and if it fails, then check with a more reliable mechanism.
In the general case, I think it's not quite enough.
Consider the case where you have two different instances (addresses), but the same guts/internals.
If it's really the latter, then maybe your short-cut would work: your short-cut is really one type of a shallow comparison.
For instance, if you can guarantee that every event would have a different timestamp anyways, which would cause two different instances to return false anyhow (and you care about timestamp for comparison purposes), using the short-cut would be fine.
Otherwise, do it the normal way (a deep comparison or at least a one-level shallow comparison).
Ultimately, it comes down to your interpretation/semantics of what equals means, in this case.
If you do choose to compare addresses, I recommend that you put comments about your implementation so that future readers of your code will understand that you have put thought into your implementation and this is really what you intended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With