1

I'm working on some kind of smart pointer technique but there is one piece I'm missing. I tried several combinations but the logic is as follow:

UInt *obj = new UInt;
UInt *ref;
ref = obj;

delete obj;
obj = NULL;

if (ref == NULL)
{
    // It works
}
else
{
    // It failed
}

Is there any way to hit "It Works" without setting ref to NULL explicitly?

EDIT:

A more appropriate scenario would be something like this:

class A
{
public:

    A(): ref(NULL) {}
    ~A()
    {
        if (ref != NULL)
            delete ref;
    }
    int *ref;
};

    int *obj = new int;
    A *host = new A();

    host->ref = obj; ???

    delete obj;
      obj = NULL;

    if (host->ref == NULL)
    {
        // It works.
    }
    else
    {
        // It failed.
    }

...

Can't use int*& ref as a class member though.... must be close.

neosettler
  • 261
  • 3
  • 14

3 Answers3

4

As you say, you should be using a smart pointer:

#include <memory>

std::shared_ptr<UInt> obj = std::make_shared<UInt>();
std::weak_ptr<UInt> ref = obj;

obj.reset();

if (ref.expired())
{
    // It works
}
else
{
    // It failed
}

Don't try managing your own memory when the standard library has facilities to do it for you.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Exactly, so that people who read your code will not need to read and understand your own implementation, when there is a standard that everybody knows. Also, most probably, standard will have it better than yours. – Etherealone Feb 01 '13 at 16:50
  • True, I never use the std lib, I guess I could give it a try. I'm still interested how I could accomplish the example. – neosettler Feb 01 '13 at 17:10
3

Declare ref as a reference to pointer

Uint*& ref = obj;

ref will now refer to the obj pointer.

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
1

Intially both obj and ref point to the (same) UInt instance. Then you delete the instance and set obj to NULL. But ref is just like any other regular pointer, so it still points to the deleted instance.

Instead you can create a reference variable, or in this case a 'reference pointer' by adding & to the declaration:

Uint*& ref = obj;

Then ref really refers to obj and keeps the same value (pointer) as obj.

Veger
  • 37,240
  • 11
  • 105
  • 116
  • Oh excellent, I used this example for simplicity sake but what if ref is a class member? – neosettler Feb 01 '13 at 17:13
  • http://stackoverflow.com/questions/892133/should-i-prefer-pointers-or-references-in-member-data provides some details, cons and pros of references as class members vs pointers – Veger Feb 01 '13 at 20:18