In C++, pointers generally have a lot more functionality associated with them than is really necessary. A class template that wraps a pointer and removes most of the less-used features (arithmetic, indexing, deletion). Each function could then decide how powerful a pointer it requires and take the appropriate type.
Would using such types make sense in an actual project, though? Are errors caused by unintentional arithmetic/deletion common enough to justify the additional effort?
To clarify: I am considering this as a system alongside existing weak_ptr
, shared_ptr
, unique_ptr
— those three are great when ownership is involved, but sometimes non-owning nullable or reseatable references are useful.
Best Answer
For me "non-owning pointers" are nearly non-existant. If I will be storing a pointer to an object in a member variable, then there is some kind of ownership in play, even if it is weak ownership. If this is for passing arguments to a method, then there are references (which have none of the problems you mention).
The only exception I can think of is when iterating through a raw array, maybe serializing/deserializing binary data. In that case I want to be able to do pointer math, but not deletion. But it would be incredibly difficult to accidently delete a pointer, especially when I hardly use delete anyways!