0

I have a simple problem like this!

class1 *a = new class1();
class1 *b = a;

delete a;
a= NULL;

Now I want to check if b is NULL (or is deleted) also, but b always point to where a point previously. This is problematic when I want to use b, but a already deleted before!

if (b){
    //do something here
}

Thanks for reading!

greenpig83
  • 13
  • 4

2 Answers2

4

There is no way to have b update automatically after a has been NULLd. The question code also illustrates why setting a pointer to NULL after it's object has been deleted is partial, at best, and that a non-NULL pointer does not guarantee that a pointer is pointing to a valid object.

Use a std::shared_ptr<class1> instead, as there is shared ownership of the pointed-to object:

std::shared_ptr<class1> a = std::make_shared<class1>();
std::shared_ptr<class1> b = a;

the dynamically allocated object will be destructed with both a and b go out of scope.

See What C++ Smart Pointer Implementations are available? for an overview of available smart pointers.

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
4

As some have suggested, using a shared pointer will make this easier.

If you want to do it the raw way, here is why *b still points to the original value of a

When you say class1 *b=a you are taking a copy of the pointer value of a. So regardless of what you do to a itself, b hangs on to this original value.

If you wanted it to change along with a, you would need to assign a reference to a, or a pointer to the a pointer

class1 **b = &a;

So now, think what happens when you dereference b, what value is that pointing to?

it will point to your original class1 *. So, once you set a=NULL, you now have a pointer b that points to the value of a, or NULL

75inchpianist
  • 4,112
  • 1
  • 21
  • 39
  • I think this is better than the shared pointer, as it preserves the flow of the original code. A shared pointer would alter the lifetime of the object to not match the original code. – Ryan Witmer May 09 '13 at 18:42
  • this is true, though it requires more memory management than a shared pointer would require. – 75inchpianist May 09 '13 at 18:45
  • Yeah I think this approach work really well, but it will make the code look more Pointer-Way, a is already pointer, now b is a pointer of pointer ^^. Never try this before, but i think i will try to use it from now in some case! Thanks! – greenpig83 Nov 29 '13 at 04:21