Pass weak this pointer to its own function

628 views Asked by At

Is it a good idea to have code like this: Any pitfalls ? Is it a better design to use shared this pointer ?

class X { 
   public:
   void foo();
   void bar2(const boost::weak_ptr<X>& x); 
};

void X::foo() {}
void X::bar2(const boost::weak_ptr<X>& x) {}
void foo() 
{
    const boost::shared_ptr<X> x = boost::make_shared<X>();
    boost::weak_ptr<X> weakX(x);
    x->bar2(weakX);
}

int 
main()
{
    foo();
    return 0;
}
1

There are 1 answers

0
Kleist On

If the argument passed in to the function is supposed to always be a weak_ptr-version of this you have a problem. There is nothing in the code enforcing this behaviour, so a user of your class could just as easily pass a weak_ptr to another object of class X.

If what you need is for bar2 to be able to pass on a shared_ptr to this, a better solution is to use std::enable_shared_from_this

Example

#include <iostream>
#include <memory>

struct Foo : public std::enable_shared_from_this<Foo> {
    Foo() { std::cout << "Foo::Foo\n"; }
    ~Foo() { std::cout << "Foo::~Foo\n"; } 
    std::shared_ptr<Foo> getFoo() { return shared_from_this(); }
};

int main() {
    Foo *f = new Foo;
    std::shared_ptr<Foo> pf1;

    {
        std::shared_ptr<Foo> pf2(f);
        pf1 = pf2->getFoo();  // shares ownership of object with pf2
    }

    std::cout << "pf2 is gone\n";   
}

Output:

Foo::Foo
pf2 is gone
Foo::~Foo

from http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this