Reputation: 7
I want to make many objects of type "Student" and store them so they can be used throughout the program. I'm also required to print out messages when a student is created and destroyed, but when i put the "destroyed" message in the destructor it'll appear whenever I change instance to create the next student cause the destructor is called. Is there a way to bypass that and only have the destructor be called for each object at the end of my program?
This current piece of code has each student destroyed whenever the next one is to be created (with each for loop), and then again "redestroyed" at the end of the program. I only want them to be deleted at the end.
#include <iostream>
#include <string>
class Student{
// members
public:
Student(){}
Student(std::string name, int floor, int classroom ){
std::cout<<"Student created\n\n";
// assignments
}
~Student(){std::cout<<"Student destroyed\n\n";}
// methods
};
int main(int argc, char** argv) {
Student* S=new Student[5];
for (int i=0; i<5; i++){
S[i]=Student("example", 1,1); //makes 5 students and stores them
}
// rest of the program
delete[] S;
return 0;
}
Upvotes: 0
Views: 63
Reputation: 409404
The destructor you see from the loop is not the array elements being destructed, but rather the temporary object that you create by Student("example", 1,1)
.
The statement
S[i]=Student("example", 1,1);
is essentially equal to
Student temporary_object("example", 1, 1);
S[i] = temporary_object;
If you want to create five objects, where every object is initialized exactly the same (which is what you're doing) then use a std::vector
with explicit initializer:
std::vector<Student> S(5, Student("example", 1,1));
This will still call the destructor once, for the temporary object you create in the std::vector
constructor call.
There is a way to skip the creation of temporary objects, but that also requires the use of vectors:
std::vector<Student> S;
S.reserve(5); // Reserve memory enough for five elements
for (unsigned i = 0; i < 5; ++i)
{
S.emplace_back("example", 1, 1); // Construct in-place in the vector,
// no temporary object creted
}
Note that the reserve
call is important to avoid reallocations of the vector, which involves possible copying of data and destruction of the old data.
Upvotes: 1