Tom Deseyn
Tom Deseyn

Reputation: 1885

No standard way to compare smart pointer with regular pointer?

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.

Upvotes: 23

Views: 13339

Answers (4)

utnapistim
utnapistim

Reputation: 27375

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").

Upvotes: 17

James Kanze
James Kanze

Reputation: 153977

The main reason is probably because if you are using the standard smart pointers, there shouldn't be any raw pointers to the object. Having a raw pointer to the object is almost a guarantee that at some point during maintenance, someone will end up creating a second smart pointer from it, with disasterous consequences. (The one exception is a null pointer, and the standard does allow comparison with a null pointer constant.)

Upvotes: -2

Some programmer dude
Some programmer dude

Reputation: 409356

Because the comparison operators don't compare what is pointed to, only the actual pointer. And as the smart pointers have "ownership" of the actual raw pointer, any other raw pointer can't be the same as the compared-to smart pointer.

Upvotes: 3

Tony The Lion
Tony The Lion

Reputation: 63250

You can just do smart_ptr.get() == raw_ptr, what is wrong with that?

Upvotes: 10

Related Questions