// shared_ptr_grades.cc // for g++ compiled with: // g++ -std=c++11 -o shared_ptr_grades shared_ptr_grades.cc #include #include #include #include // for shared_ptr using namespace std; class ClassGrades { private: string Name; int* Grades; public: ClassGrades(string inName) { cout << "In constructor for record " << inName << endl; Name = inName; Grades = new int[3]; // assume 3 assignments for (int i=0; i<3; i++) { Grades[i] = 0; } } ~ClassGrades() { cout << "In destructor for record " << Name << endl; if (Grades != NULL) delete [] Grades; } int& operator [] (int Index) { if (Index >=0 && Index < 3) { return Grades[Index]; } } void PrintGrades() { cout << "Student " << Name << " has grades: "; for (int i=0; i<3; i++) { cout << Grades[i] << " "; } cout << endl; } }; int main() { // This time we will dynamically allocate students using new, and we // will handle the pointers using smart pointers so we don't have to // explicitly remember to delete the ClassGrades objects vector> StudentList; // Just make 2 of them for simplicity int NumStudents = 2; for (int i=0; i NewStudent(new ClassGrades("John Smith")); (*NewStudent)[0] = 70; (*NewStudent)[1] = 72; (*NewStudent)[2] = 86; StudentList.push_back(NewStudent); } else if (i==1) { shared_ptr NewStudent(new ClassGrades("Sally Brown")); (*NewStudent)[0] = 82; (*NewStudent)[1] = 90; (*NewStudent)[2] = 80; StudentList.push_back(NewStudent); } } // iterate through the vector for (int i=0; iPrintGrades(); } // we created the ClassGrades objects with new but they will delete // themselves when the smart pointers go out of scope }