if you know p is defined as a pointer to an integer, how can you know it is actually allocated a space and has a integer to point to, so it's safe to use *p? How can a "null pointer exception" be thrown in this case? |
If all you have is the pointer and no other information about the allocated buffer, then there is no way to know.
This is one of the many reasons why using pointers directly is "evil" and why container classes are generally preferred.
Generally... to use pointers safely, you need to know other information (such as the number of elements allocated, whether or not anything at all is allocated, who the owner is, etc). All this information can be bundled in a class that you pass around instead of passing around the pointer.
(but it would seem to me that it is very hard too be careful enough when you assign a pointer to another directly.) |
It is kind of... but not really. It depends entirely on the circumstance.
If A owns the pointer and gives the pointer to B. Then you just need to be sure that A's lifetime is as long or longer than B's.
If A and B have independent lifetimes and there's no way to know whose life will end first, then you probably don't want to pass pointers around this way. If A dies (and frees the pointer) while B is still alive and using the pointer, you're hosed.
I guess it would be OK if the pointer is not pointing to int, char, double or string - the 4 basic build-in types. |
string isn't really a built in type. It's a complex class. There are also many other types, like float, short, long and bool. Not counting unsigned counterparts, extended types (long long), and bitfields.
If it points to a user-defined type derived from the class "Object", the "IsNull" function should normally be implemented so that it is possible to call " *p.IsNull()" to check if pointer p has already been deleted. |
This doesn't work anyway.
An object can't check itself to see if it's already been deleted because if it's already been deleted
then it's too late and there's nothing it can check.
Unless I'm missing something, I don't see how an IsNull function could be implemented legally in C++. Not unless it's incredibly complex and impractical.