Why doesn't the C++ standard include comparison operators to compare smart pointers (unique_ptr, shared_ptr, ...) with regular pointers (T*)?
Tom
update I am not looking to find out how it can be done. The question is why is it not defined as part of the C++ standard? For unique_ptr and shared_ptr such definitions would be trivial.
A use case for this is the following: Class A has a map with unique_ptr keys. unique_ptr is used for memory management. When a user of class A passed a regular pointer, a lookup is performed inside this map. Unfortunately, the standard doesn't define the comparision operators.
Why doesn't the C++ standard include comparison operators to compare smart pointers (unique_ptr, shared_ptr, ...) with regular pointers (T*)?
The principle behind this decision is usually stated as "make your interfaces easy to use correctly and difficult/impossible to use incorrectly".
Conceptually, a smart pointer and a raw pointer are not the same.
A smart pointer imposes restrictions (i.e. "unique_ptr is a pointer, but you cannot have multiple copies"). Although they behave like pointers (to a point - if you will excuse the pun), they have different semantics.
That is, if you have:
int *p1 = new int{5}; std::unique_ptr<int> p2{new int{5}}; p1 == p2.get();
The comparison is easy to do, explicit, and makes it obvious that you are comparing apples and apples (easy to understand what's going on - you're comparing with the value of a raw pointer).
Having a custom comparison operator on the other hand would raise weird questions ("a unique_ptr is unique; how can you compare it with something else? - if it's unique, it should always be different").
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