ben
ben

Reputation: 1849

Why is a second pointer to an Object not set to NULL but the Object pointer?

#include <iostream>

using namespace std;

class Object{};

class Connection
{
  public:
    Connection(Object * _obj);
    Object * obj;
    void status();
};

Connection::Connection(Object * _obj)
{
  obj = _obj;
}

void Connection::status()
{
  cout << obj << endl;
}


int main() {
  Object * myObj = new Object();

  Connection * myConn = new Connection(myObj);

  delete myObj;
  myObj = NULL;

  cout << myObj << endl;
  myConn->status();
  /*
  Output is:

  0
  0x25ec010

  but should be:

  0
  0

  */
}

I thought I am only working with pointers in this example. So I don't understand why the pointer in "myConn" is not set to NULL too, because there are two pointers which point to the same address.

Upvotes: 0

Views: 163

Answers (4)

dmirkitanov
dmirkitanov

Reputation: 1396

It shouldn't be 0 because you are copying pointer value. Try using references (&) instead.

Maybe this is not a best example, and boost::shared_ptr will be better solution, but this code will work:

 // skipped...
 class Connection
 {
 public:
   Connection(Object **_obj);
   Object **obj;
   void status();
 };

 Connection::Connection(Object **_obj) : obj(_obj) { }
 void Connection::status() { cout << *obj << endl; }

 int main()
 {
   Object * myObj = new Object();
   Connection * myConn = new Connection(&myObj);
 // skipped

Upvotes: 1

Sander De Dycker
Sander De Dycker

Reputation: 16243

A pointer is a separate entity from the object it points to.

Several pointers pointing to the same object have no relation with each other (other than the fact that they point to the same object), so they have to be managed separately.

This fact causes a problem in the code example you posted : after deleting the object using the myObj pointer, you correctly set the pointer to NULL to indicate that it no longer points to a valid object. However, the myConn->obj pointer still points to the already deleted object (ie. the pointer is no longer valid).

The use of a shared pointer (boost::shared_ptr) can help in this kind of situation.

Upvotes: 0

Drake
Drake

Reputation: 3891

Connection::obj doesnt point to myObj, it points to the value that myObj held. So if you want to fix it you have to manually set the value to null in a function. Or make a second pointer that holds a pointer to a obj, and check if that one is null but would be over complicating it.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477060

*myConn made a copy of your myObj pointer (when you said obj = _obj;). The copy didn't get set to null. (But it's still pointing to a now invalidated address, so don't dereference it!)

Upvotes: 1

Related Questions