|
Boost Users : |
From: Jeff Foster (jfoster_at_[hidden])
Date: 2008-05-15 14:03:27
See boost::enable_shared_from_this
(http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/enable_shared_from_this
.html)
> -----Original Message-----
> From: boost-users-bounces_at_[hidden]
> [mailto:boost-users-bounces_at_[hidden]] On Behalf Of
> Abdo Haji-Ali
> Sent: 15 May 2008 17:00
> To: boost-users_at_[hidden]
> Subject: [Boost-users] Assigning 'this' to share_ptr
>
> 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 mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>
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