Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No standard way to compare smart pointer with regular pointer?

Tags:

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.

like image 565
Tom Deseyn Avatar asked Aug 05 '13 09:08

Tom Deseyn


1 Answers

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

like image 69
utnapistim Avatar answered Oct 26 '22 13:10

utnapistim