C++ Is it possible to determine whether a pointer points to a valid object?
No, you can't. Why? Because it would be expensive to maintain meta data about what constitutes a valid pointer and what doesn't, and in C++ you don't pay for what you don't want.
And you don't want to check whether a pointer is valid, because you know where a pointer comes from, either because it's a private part of your code that you control, or because you specified it in your external-facing contracts.
Not possible. Think of this scenario.
int *ptr = new int(10);
int *ptrDup = ptr;
delete ptr;
But ptrDup
still points to the memory location pointed by ptr
which no longer exists. So, deferencing ptrDup
results undefined behavior. But there is reference counting which is totally a different concept.