|
Boost Users : |
From: Duane Murphy (duanemurphy_at_[hidden])
Date: 2002-11-15 02:38:25
--- At Thu, 14 Nov 2002 22:36:40 -0600, Stephen Crowley wrote:
>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);
Actually the problem lies here.
Accessing this here is accessing it as a raw pointer outside of the
shared_ptr. In a word...dont do that.
I had this problem before but I was able to work around it. I dont have a
good suggestion for a solution. Basically, architecturally, I arranged to
not need to save things this way. In my case I ended up actually passing
in a shared_ptr to solve the problem. You can duplicate a shared_ptr, you
cant duplicate a raw pointer this way.
I have found this to be a difficult thing to deal with in a couple of
corner cases. Where I wanted the raw pointer to know that it was shared,
but I couldnt do that. This would be an intrusive shared_ptr
implementation rather than the current non-intrusive one. In an intrusive
implementation, the count information is actually part of the shared
object rather than an extra pointer. There are certain advantages to the
intrusive model. Of course it has is draw backs as well.
> 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();
>}
...Duane
-- "If tyranny and oppression come to this land, it will be in the guise of fighting a foreign enemy." - James Madison
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