According to cppreference.com, std::shared_ptr provides a full set of relative operators (==, !=, <, …), but the semantics of comparison aren’t specified. I assume they compare the underlying raw pointers to the referenced objects, and that std::weak_ptr and std::unique_ptr do the same.
For some purposes, I would prefer to have relative operators that order the smart pointers based on comparing the referenced objects (rather than the pointers to them). This is already something I do a lot, but with my own “dumb pointers” that behave mostly like raw pointers except for the relative operators. I’d like to do the same thing with the standard C++11 smart pointers too. So…
-
Is it OK to inherit from the C++11 smart pointers (shared_ptr, weak_ptr and unique_ptr) and override the relative operators?
-
Are there any sneaky issues I need to look out for? For example, are there any other methods I need to implement or use
usingfor to ensure things work correctly? -
For the ultimate in laziness, is there a library template available that will do this for me automatically?
I’m hoping this is an “of course you can do that, idiot!” kind of thing, but I’m a little uncertain because there are some classes in the standard library (containers like std::map at least) that you’re not supposed to inherit from.
In general, it’s not safe to inherit from anything who’s destructor is not dynamic. It can be and is done commonly, you just have to be really careful.
Instead of inheriting from the pointers, I’d just use composition, especially since the number of members is relatively small.
You might be able to make a template class for this
Obviously, the simplicity of the wrapper reduces you to the lowest common denominator for the smart pointers, but whatever. They’re not exactly complicated, you could make one for each of the smart pointer classes.
I will provide a warning that I don’t like the way
==works, since it may return true for two pointers to different objects. But whatever. I also haven’t tested the code, it might fail for certain tasks, like attempting to copy when it contains a unique_ptr.