Oh darn, I was busy and you posted a lot while I was gone.
But here are my thoughts
Yes, correct. The first example is on the stack, the second is on the heap. So if you need the data to outlive the scope its defined in, you'll need to use Person*'s.
I realized this could get super complicated, depending on the specifics what can happen. Might be a bit above my head to know the most efficient solution, but:
So, let's say we have it set up so that both Dad and Mom give birth to Son and Daughter. Dad has Mom set as spouse. Mom has dad set as Spouse. Dad and Mom both have a vector of 2x children pointers, and those point to Son and Daughter. Let's say something bad happens and Son dies, so you want to remove him from the (living) family tree. So, we need to decide who is in charge of the memory.
Let's say you have something like this
1 2 3 4 5 6 7 8
|
Person* dad;
Person* mom;
Person* son;
Person* daughter;
// ...allocate and set up relationships
TellParentsChildDied(dad, mom, son);
|
So now what? Once you tell mom and dad that their son died, they can each remove the son from their vector. But who is actually in charge of deleting the son's heap data (burying him?). We don't know.
One solution is to use shared_ptrs. You'd have to re-work your code, though. Might be complicated. I'm not an expert in this, although others in this forum are much more comfortable with this, hopefully they'll see the thread.
|
shared_ptr<Person> son = make_shared("Billy");
|
shared_ptrs do reference counting to ensure they don't delete heap-allocated memory that is still being referenced by someone else.
Once the last
std::vector<std::shared_ptr<Person>>
vector removes the son's shared_ptr, the destructor of the shared_ptr should know to decrement its reference count, and delete the actual data. RIP son.
But I suggest searching google for unique_ptr or shared_ptr guides, since I remember there being a ton of gotchas, but it's been a while since I've coded anything serious with them.
Person( const Person& self, Person* spouse );
What is this supposed to do? Copy self, and then re-assign the spouse? (Got a divorce :p) I think that's valid, but might seem like a confusing interface as opposed to just re-assigning the spouse.
________________________________
Edit: I also don't think you should have to deep copy or allocate anything just to compare two Persons (== operator).