I want to define two classes A and I in a such a way that their objects respect this kind of relationship:
i1 -----------a1
|------a2
|----a3
An instance of the class
Ipoints to zero, one, or many instances of the classA.An instance of the class
Apoints to only one instance of the classI.An instance of class
Ican be without any instances of classA, but an instance of classAmust have an instance of classI"attached".
In order to statisfy these conditions, I declared the two classes as follows:
class I;
class A
{
private:
std::string as;
std::shared_ptr<I> iA;
public:
A(std::string aTxt);
A();
~A();
};
class I
{
private:
std::string ip;
std::vector<std::unique_ptr<A>> as;
friend class A;
public:
I(std::string i);
~I();
};
And in the source file, I defined the two classes in this way:
A::A(std::string aText)
{
as = aText;
}
A::A()
{
as = "";
}
A::~A()
{
}
I::I(std::string i)
{
ip = i;
}
I::~I()
{
}
Questions:
When the instance
iof the classIis deleted, all the attached instancesaof the classAhave to be removed. How to set this mechanism in the destructor ofI?When an instance
aof the classAis deleted, the instanceiof classIthat it points to is still pointed by other instancesaof the classA. How to be sure that once all the instancesaof the classesAare deleted, the instanceiof the classIcan still exist, even if no instances ofApoint to it?
The
vectorofunique_ptrs will handle that for you automatically. You don't need to write any extra code for it. When an instance ofIis destroyed, the destructor of thevectorinstance will call the destructor of theunique_ptrinstances, which will destroy theAinstances.Ashould not have a smart pointer (shared_ptr) toIat all, asAdoes not controlI's lifetime. A non-owning raw pointer will suffice in this case.Try this: