RE: [Boost-Users] using 'this' with shared_ptrs
You initialises two shared_ptr with the same raw pointer. As a consequent the destructor is called twice, as you will have two different shared_count object which will calls delete as the count become zero.
Try to use weak_ptr as a member:
-----------------------------------
typedef shared_ptr<MyClass> MyClassPtr;
class MyClass
{
public:
MyClass();
~MyClass();
void setOriginal(MyClassPtr);
MyClassPtr makeCopy();
weak_ptr<MyClass> original;
};
MyClass::MyClass()
{
cout << "constructor called " << this << endl;
}
MyClass::~MyClass()
{
cout << "destructor called " << this << endl;
}
void MyClass::setOriginal(MyClassPtr p)
{
original = p;
}
MyClassPtr MyClass::makeCopy()
{
return MyClassPtr(original);
}
main()
{
MyClassPtr oc(new MyClass);
oc->setOriginal(oc);
MyClassPtr cc = oc->makeCopy();
}
---------------------------------
Per
-----Original Message-----
From: Stephen Crowley [mailto:stephenc@digitalpassage.com]
Sent: 15. november 2002 05:37
To: Boost-Users@yahoogroups.com
Subject: [Boost-Users] using 'this' with shared_ptrs
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
participants (1)
-
Per Kristensen