Home > Software design >  Is it possible to determine if a pointer points to a valid object, and if so how?
Is it possible to determine if a pointer points to a valid object, and if so how?

Time:05-14

I was reading C Is it possible to determine whether a pointer points to a valid object? and the correct answer in this thread is that no, you can't do that, but the thread is quite old now and I wanted to know if anything has changed. I read that with smart pointers that would be possible. So how could that be achieved?

CodePudding user response:

Is it possible to determine if a pointer points to a valid object

No, it isn't generally possible to determine whether a pointer points to a valid object.

I wanted to know if anything has changed

Nothing has changed in this regard.

I read that with smart pointers that would be possible. So how could that be achieved?

Unless you misuse it in a bad way, a smart pointer is never invalid. As such, there is no need to check whether it is valid or not. It should either be null or point to a valid object.

Weak pointer is a special kind of smart pointer that doesn't own an object directly, but it points to an object owned by shared pointer(s). The pointed object may be destroyed when no shared pointer points to it anymore. It's possible to ask the weak pointer whether that has happened or not. This state is somewhat analogous to being invalid, except the state is verifiable.

So how could that be achieved?

You can std::make_unique or std::make_shared to create a dynamic object owned by a smart pointer. The choice between them depends on what kind of ownership you need: unique or shared. Weak pointers can be created only from shared pointers.

  • Related