How do i check whether the pointer is deleted or not in C++
There is no way to check whether a pointer is deleted or not in C++.
There is also no need to check whether a pointer was deleted. If you get a pointer from a new-expression, and you haven't yet deleted the pointer earlier, then it is safe to assume that delete will release that memory.
Its not about trusting the compiler. I just want to confirm whether it is deleted or not. If its deleted its good, but if it is not deleted then ...
Since it is not possible to test whether a pointer has been deleted or not, the trick is to structure the program such that there is never doubt about the state of the pointer.
The typical solution is to store the pointer as a private member variable of a class described as a "smart pointer", and to never let the post condition of any function of that class to leave the pointer in a deleted state. This establishes a class invariant that guarantees the validity of the pointer throughout the entire lifetime of the object and therefore there is never need to find out when the pointer can be deleted.
The standard library provides smart pointer classes for you, so there's hardly ever need to write delete
or delete[]
yourself.
In the case of dynamic arrays that you use as an example, you don't need to use any pointers. You can use std::vector
instead:
{
std::vector<int> p(10);
}
// memory was freed; no need to test