From https://timsong-cpp.github.io/cppwp/basic.compound#3 :
Every value of pointer type is one of the following:
- a pointer to an object or function (the pointer is said to point to the object or function), or
- a pointer past the end of an object ([expr.add]), or
- the null pointer value for that type, or
- an invalid pointer value.
After using a pointer to explicit call an object's destructor, which of these four kinds of value does the pointer have? Example :
#include <vector>
struct foo {
std::vector<int> m;
};
int main()
{
auto f = new foo;
f->~foo();
// What is the value of `f` here?
}
I don't believe it can be a pointer to an object or function. There is no longer an object to point to and it is not a function pointer.
I don't believe it can be a pointer past the end of an object. There wasn't any sort of pointer arithmetic and no array is involved.
I don't believe it can be a null pointer value since the pointer is not nullptr
. It still points to the storage the object had, you could use it to perform placement new
.
I don't believe it can be an invalid pointer value. Invalid pointer values are associated with the end of storage duration, not object lifetime. "A pointer value becomes invalid when the storage it denotes reaches the end of its storage duration". The storage is still valid.
It seems to me like there is no pointer value the pointer could have. Where did I go wrong?
f
doesn't change during, or as a result of, the explicit call of the destructor. Because of the destructor call,f
now points at an object that has ceased to exist. Any attempt to use that object (e.g. dereference that pointer) gives undefined behaviour. – Pebanullptr
and test non-equal. The standard specifies that using an object outside its lifetime gives undefined behaviour. The standard also says nothing about what the meaning of the value of the pointer is after the object's lifetime has ended - which means, if you attempt to test "validity" of that pointer (beyond comparing it withnullptr
) you are in the realms of undefined behaviour. – Peba