I have two classes. One class(Person) has a vector collection composed of pointers of the other class(Student). At run time, the Person class will call a method which will store a pointer to a Student class in the vector. I have been trying to do this with smart pointers to avoid Memory leak issues that can arise but I am struggling to do so. How would I go about it?
My goal is for the Person class to have handles to objects that exist somewhere else in the code
Class Student
{
public:
string studentName
Student(string name){
studentName = name;
}
}
Class Person
{
public:
vector <Student*> collection;
getStudent()
{
cout << "input student name";
collection.push_back(new Student(name));
}
}
CodePudding user response:
You don't need to use smart pointers here. Place the objects directly into the vector and their lifetime is managed by the vector:
std::vector<Student> collection;
collection.emplace_back(name);
CodePudding user response:
Building on the other answer, you should store the Student by Value.
From a simplistic point of view, there are kinda three ways to store something in a vector:
std::vector<std::shared_ptr<Student>> students;
// an array of smart pointers
std::vector<Student*> students; // array of pointers
std::vector<Student> students; // array of objects stored by value.
The difference comes down to a range of things: ownership, lifetime, whether it is stored on the heap or stack.
In this case, you will likely want to store your students by value because we can safely say the 'Person' class 'owns' the list of students. When a member variable is stored by value, it sticks around only as long as the scope within which it is placed sticks around. In this case, the vector of students only sticks around so long as its parent object, an instantiantion of 'Person', sticks around.
If you are really set on storing stuff by smart pointer, however, you can do this:
std::shared_ptr<Student> myStudent = std::make_shared<Student>(name);
students.push_back(myStudent);