My idea is to print the object it points to. I think a valid pointer should have a valid object. If we try to print out the object we verify if the pointer is valid. Am I right?
I think a valid pointer should have a valid object.
Yes, that's the definition of a valid pointer.
If we try to print out the object we verify if the pointer is valid.
Unfortunately, you can't. You can check whether the pointer is null; but if it wasn't initialised properly, or if it pointed to an object that's been destroyed, it will be neither valid nor null.
If you want a pointer that's smart enough to know whether it's valid, you'll need a smart pointer.
Your code should be smart to track pointers and avoid using un-allocated or un-initialized pointers. Validity or invalidity are relative concepts in the code. Try to use smart pointers.
For bare pointers, you can initialize them by null if you don't know the pointer will be initialized at the future or not. Then before using the pointer, you can check if it's null or not.
But this is not enough, ill-formed codes can have invalid pointers and its programmer will find them hard. For example consider returning a pointer to a local temporary object which is going to destroy after exiting the function. Therefor, you should manage them in the code.
First try to avoid pointers. If you need them, use smart pointers. If you have to use bare pointer write a well-formed code and track pointers by correct usage of allocation/deallocation and null value.
来源:https://stackoverflow.com/questions/20101640/can-we-check-a-pointer-to-make-sure-it-is-a-valid-address