如何使用智能指针来存储

RMC*_*DEV 0 c++ pointers class smart-pointers

我有两节课。一个类(Person)有一个由另一类(Student)的指针组成的向量集合。在运行时,Person 类将调用一个方法,该方法将在向量中存储指向 Student 类的指针。我一直在尝试使用智能指针来做到这一点,以避免可能出现的内存泄漏问题,但我正在努力这样做。我该怎么办呢?

我的目标是让 Person 类拥有代码中其他地方存在的对象的句柄

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));
   }
}
Run Code Online (Sandbox Code Playgroud)

Ayx*_*xan 6

您不需要在这里使用智能指针。将对象直接放入向量中,它们的生命周期由向量管理:

std::vector<Student> collection;

collection.emplace_back(name);
Run Code Online (Sandbox Code Playgroud)