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;
}
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 ofclass X
.If what you need is for
bar2
to be able to pass on ashared_ptr
tothis
, a better solution is to usestd::enable_shared_from_this
Example
Output:
from http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this