Imagine the following classes in java or C#:
class A
{
B b;
//some other stuff
public A(B b) {this.b = b;}
}
class B
{
A createA() {return new A(this); }
}
then we would use it e.g.
A complicatedCreateA()
{
B = new B();
return b.createA();
}
and the virtual machine / CLR would make sure we don't leak memory.
How can I implement a similar pattern in C++ so that I don't leak memory and reference cleaned resources?
EDIT: To make it more clear I am specifically worried about what happens if I call createA() more than once, and when the different objects A will have different lifetimes, e.g.:
A anotherMethod()
{
B = new B();
A a = b.createA();
//use a locally, or use with yet another object C, etc.
return b.createA();
}
I have the basic understanding how smart pointers work in C++. However, even if I do something like:
boost::shared_ptr<B> b(new B());
then I don't have access to this smart pointer from within B, so I can't pass it to A. And how otherwise A can make sure that the corresponding object B gets deleted not too late and not too early?