Boost logo

Boost Users :

From: Abdo Haji-Ali (abdo.haji.ali_at_[hidden])
Date: 2008-05-15 11:59:44


Hi,

I was recently introduced to boost's shared_ptr and I really liked the
fact that freeing memory is done automatically.
So I started using it in almost every case, instead of the dangerous
C-style pointers.
However, I'm having a design issue concerning shared_ptr. Here's a
snippet that describes my situation:

<code>

#include <boost/shared_ptr.hpp>

class MyClass;
typedef boost::shared_ptr<MyClass> MyClassPtr;

class MyClass {
public:
   // Fields
   virtual void CallUtility(); // May be overrided later

   static MyClassPtr CreateMyClass() {
       return MyClassPtr(new MyClass());
   }
private:
   MyClass();
};

void UtilityFunc(MyClassPtr pClass) {
   // Do things with pClass
}

void MyClass::CallUtility() {
   // Do stuff
   // How can I pass 'this' to UtilityFunc?
   // without freeing it, of course
   UtilityFunc(MyClassPtr(this)); // How can I pass 'this' to UtilityFunc?
   // Do stuff
}

</code>

Note that MyClass is always created using 'new' on the heap (never on
the stack).
Also note that a function is not my only case. I also have classes
that store a MyClassPtr
and there's a function in MyClass that does something like this:
ClassA MyClass::CreateClassA()
{
   ClassA a;
   a.myClass = this; // How can I do this
   return a;
}

One way to solve this would be to pass a MyClassPtr parameter to the
CallUtility(), and then use
it instead of this. So it becomes like this:
pMyClass->CallUtility(pMyClass);

Which is ugly, to say the least.
Do you have another way? Am I missing something trivial here?

--
Abdo Haji-Ali
Programmer
In|Framez

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