Boost logo

Boost Users :

From: Stephen Crowley (stephenc_at_[hidden])
Date: 2002-11-14 23:36:40


How is someone supposed to use 'this' when setting a member of another class
to point back to it?

Here is an example.. when you run it, this will happen.

constructor called 0x804af10
constructor called 0x804af48
destructor called 0x804af48
destructor called 0x804af10
destructor called 0x804af10

The last destructor is called twice! The only way I can think to get around
this add a member to the class called "shared_ptr<MyClass> thisptr" which is
initialized to "this" in the constructor and over-ride the assignment
operator or something.. will that work?

------------------------
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <iostream>

using namespace std;
using namespace boost;

class MyClass;

typedef shared_ptr<MyClass> MyClassPtr;

class MyClass
{
 public:
   MyClass();
   ~MyClass();
   
   MyClassPtr makeCopy();
   MyClassPtr original;
};

MyClass::MyClass()
{
   cout << "constructor called " << this << endl;
}

MyClass::~MyClass()
{
   cout << "destructor called " << this << endl;
}

MyClassPtr MyClass::makeCopy()
{
   MyClassPtr mc(new MyClass);
   mc->original = MyClassPtr(this);
   return mc;
}

main()
{
   MyClassPtr oc(new MyClass);
   MyClassPtr cc = oc->makeCopy();

   // the problem lies here
   // when cc's reference count is 0 it will be deleted, which will
   // in turn decrease its 'original' reference count which will be 0, thus
   // causing it to be deleted as well even though it is still being used by oc!
   cc.reset();
}
-----------------------------------

-- 
Stephen

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net