|
Boost Users : |
From: Fabian Sturm (f_at_[hidden])
Date: 2007-04-16 18:14:56
Hi!
I used the boost shared pointers for quite a while successfully but now
ran into a problem I don't have a nice solution yet.
I have a class A which has a vector of B classes. I now need to get from
the class A to all Bs which is easy (iterating over the vector) and I
need to get from any B to A (which I handle with a weak pointer)
But now I need to implement a copy method to get a "real" copy of A and
not a pointer to the shared instance.
How would I do that? The copy also points to copies of the Bees aka.
deep copy.
My current solution looks like this:
class A;
class B;
typedef boost::shared_ptr< A > A_SP;
typedef boost::weak_ptr< A > A_WP;
typedef boost::shared_ptr< B > B_SP;
class A : public boost::enable_shared_from_this< A >
{
public:
int x;
int y;
std::vector< B_SP > bees;
void addB ( B_SP b );
A_SP clone ();
};
class B
{
public:
A_WP weakA;
int c;
B_SP clone ();
};
void A::addB ( B_SP b )
{
b->weakA = shared_from_this();
bees.push_back ( b );
}
A_SP A::clone ()
{
A_SP newA ( new A );
newA->x = x;
newA->y = y;
for ( std::vector< B_SP >::const_iterator it = bees.begin ();
it != bees.end ();
++it )
{
newA->addB ( (*it)->clone () );
}
return newA;
}
B_SP B::clone ()
{
B_SP newB ( new B );
// note I can't initialize the weak_ptr here
newB->c = c;
return newB;
}
int main()
{
A_SP a ( new A );
B_SP b ( new B );
a->addB ( b );
// Now make a deep copy of a
A_SP newA = a->clone();
return 0;
}
Any ideas how this could be done more beautiful? Or more C++ish?
Every help is greatly appreciated, since I still need to get accustomed
to
C++.
Thanks a lot, Fabian
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net