开发者

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

开发者_如何学C#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.


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


*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!)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜