To be more specific:
class B;
class A
{
public:
A(B &b) : _b(b) { }
~A() { _b.do_something(); }
private:
B &_b;
};
class B
{
public:
B() { }
/** other methods */
~B()
{
for (std::list<A*>::iterator it = _bees.begin(); it != _bees.end(); ++it) {
delete *it;
}
}
void do_something();
private:
std::list<A*> _bees;
};
Is it ok to do that?
You are referencing
binA::~A ()and not_b, which will not compile. Assuming that you meant_b, then answer is – it depends. It depends on a lifetime of the object of classBthat is being references byA. If object of classBis destroyed before destructor ofAclass is called, then it is not OK, otherwise it is OK. In either case this code is not very fool proof, and many will consider re-designing to make it less dangerous.If there is no strong guarantee that
Bwill still be there whenAis destroyed, then you need to do a bit a re-design. You can, for example, storeBby value (copy it), or use reference counted or other “smart” pointers.