我有兩節課。一個類(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));
}
}
uj5u.com熱心網友回復:
您不需要在這里使用智能指標。將物件直接放入向量中,它們的生命周期由向量管理:
std::vector<Student> collection;
collection.emplace_back(name);
uj5u.com熱心網友回復:
在另一個答案的基礎上,您應該按值存盤學生。
從簡單的角度來看,有三種方法可以將某些內容存盤在向量中:
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”類“擁有”學生串列。當一個成員變數按值存盤時,它只存在于它所在的范圍內。在這種情況下,學生的向量只在其父物件(“Person”的實體)存在時才會存在。
但是,如果你真的打算通過智能指標存盤東西,你可以這樣做:
std::shared_ptr<Student> myStudent = std::make_shared<Student>(name);
students.push_back(myStudent);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/528354.html
標籤:C 班级指针智能指针
