Can we check a pointer to make sure it is a valid address?

浪子不回头ぞ 提交于 2019-12-02 10:23:20

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!