In my program Groups will have shared pointers to Subjects; and Subjects will have weak pointers to their Groups. I want the Group to have a join() function that assigns the Subject's weak pointer to itself. Below is the minimal code for what I've tried. How do I fix the join() function?
#include <iostream>
#include <string>
#include <memory>
class Party;
class Subject
{
public:
std::weak_ptr<Party> MyParty;
};
class Party
{
public:
std::string Name;
void join(std::shared_ptr<Subject> subject)
{
subject->MyParty = std::make_shared<Party>(*this); // <---- PROBLEM
}
};
int main()
{
auto& BlueParty = std::make_shared<Party>();
BlueParty->Name = "Blue Party";
auto& Jane = std::make_shared<Subject>();
BlueParty->join(Jane);
if (auto ptr = Jane->MyParty.lock())
{
std::cout << "I am in " << ptr->Name << std::endl;
}
else { std::cout << "I have no party." << std::endl; }
return 0;
}
The program prints out "I have no party". If the assignment were successful, it should have printed out "I am in Blue Party".