I have a pointer which equals to another pointer
I'd like to check if my pointer equals to a pointer which is not null.
int* ptr0 = new int(5);
int* ptr1 = ptr0;
delete ptr0;
if ( ?? )
{
std::cout << "ptr1 equals to a null ptr" << std::endl;
}
What should I write in the condition ?
Knowing that:
Use a shared_ptr<T> combined with a weak_ptr<T>.
For example,
int main() {
std::tr1::shared_ptr<int> ptr0(new int);
std::tr1::weak_ptr<int> ptr1_weak(ptr0);
*ptr0 = 50;
// Depending on if you reset or not the code below will execute
//ptr0.reset();
if (std::tr1::shared_ptr<int> ptr1 = ptr1_weak.lock()) {
std::cout << "Changing value!" << std::endl;
*ptr1 = 500;
}
}
You can't. While in theory you could, depending on the implementation of new, check if the memory pointed to is currently in use there's no way to confirm that it's still the same object you were originally pointing to using only raw pointers.
You can use C++11 smart pointers to do something kinda like that, but I really don't think that's what you actually wanna do here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With