Hi everyone,
A while ago I asked for help about using smart pointers (ie.
shared_ptr) in cyclic situations. Weak ptrs popped out and I gave it a
try, but to be honest, I don't feel very comfortable with them.
Would using references be a bad choice? The more I think about it the
more I realize it shouldn't be any problem with them, so could it be a
good use case?
As a refresher, this would be one situation where I'm planning to use
it:
class provider {
public:
provider(observer& obs) : obs_(obs) {}
private:
observer& obs_;
};
class creator : public observer
{
public:
creator() : provider_(new provider(*this))
{}
private:
shared_ptr<providerprovider_;
};
Where observer would be an abstract class with some defined pure
virtual functions..
Could someone tell me what advantage would have using weak pointers
instead of plain references?
I don't see any danger here, as the provider class will be destroyed
while the creator is being destroyed. So the provider can be sure that
creator will always exist. Any pitfall here?
Only thing that I don't like too much is using this in the ctor, but I
think this is safe to do in this particular case..
And besides (I'm deviating the discussion a bit here), using weaker
pointers wouldn't help too much in the hypothetic case that the (weak)
pointer became invalid, as we'd need to constantly check for nullity
which is quite a pain. I thought about using the null pattern in some
situations, but if I stick to references I wouldn't mind really..
I'd appreciate any comment from you experts.
Regards.