我有两堂课。一个类(Person)有一个向量集合,该向量集合由另一个类(Student)的指针组成。在运行时,Person类将调用一个方法,该方法将在向量中存储指向某个学生类的指针。为了避免可能出现的内存泄漏问题,我一直试图使用智能指针来完成此操作,但我很难做到这一点。我该怎么做?
我的目标是让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));
}
}发布于 2022-11-07 14:46:07
这里不需要使用智能指针。将对象直接放置到向量中,其生存期由向量管理:
std::vector<Student> collection;
collection.emplace_back(name);发布于 2022-11-07 15:10:00
在另一个答案的基础上,你应该按价值存储学生。
从简单的角度来看,有三种方法可以在向量中存储某些内容:
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.区别可以归结为一系列的事情:所有权、生存期,不管它是存储在堆上还是堆栈上。
在这种情况下,您可能会想要存储您的学生的价值,因为我们可以安全地说‘人’班拥有‘学生名单。当一个成员变量按值存储时,它只停留在放置它的作用域附近。在这种情况下,只要它的父对象'Person‘的实例化存在,学生的向量就会停留在周围。
但是,如果您真的打算通过智能指针存储内容,则可以这样做:
std::shared_ptr<Student> myStudent = std::make_shared<Student>(name);
students.push_back(myStudent);https://stackoverflow.com/questions/74348362
复制相似问题