set<> with pointers

Hello.
I have made my own class, called Person. It looks like this:

class Person{
private:
string name;
set<Person *> friends;
vector<string *> msgs;
static set<string> names;
public:
Person(const string &name);
void post(string &s);
void receive(string *);
void connect (Person *p);
~Person();
friend ostream& operator << (ostream& outputStream, const Person &p);
};

Can someone tell me the difference between declearing friends with: set<Person> friends or declearing it as i do here: set <Person*> friends ? What is the benefit of declearing it with a pointer to my classtype??
set<Person> can store objects of type Person. Where set <Person*> can store pointers pointing to the objects of type Person. They are similar to set<int> and set<int*>...
You may need to overload the < operator in order to store objects.
Last edited on
Can someone tell me the difference between declearing friends with: set<Person> friends or declearing it as i do here: set <Person*> friends ?

The first one stores object, the second one stores pointers-to-objects.

What is the benefit of declearing it with a pointer to my classtype??
You can share an object between more than 1 class and at the same you have to handle the memory management yourself because pointers are not deleted automatically. You could use c++11 smart pointers to prevent memory leaks but if you have no good reason to store pointers-to-objects you're better of just storing the objects
Using pointers is necessary if you want a two-way relationship.
person1 is a friend of person2 and person2 is a friend of person1.
In this situation the friend set of person1 will contain a pointer to person2 and the friend set of person2 will contain a pointer to person1.

If you don't use pointers the friend set would contain actual Person objects so you would end up with some kind of tree structure where one person can have multiple friends but a person can only be friend of one other person. the relationship becomes one-sided.
If person1 is a friend of person2, then person2 can't be a friend of person1 because there is no way to point back to person2 from person1's friend set.
If you tried to add a person to a friend set of another person the Person object would be copied (and all his friends, and their friends, and their friends, ... would be copied) which means you end up with more persons than you had before. This is not what you want.
Last edited on
Topic archived. No new replies allowed.