#include<iostream>
#include<vector>
class Students
{
int *arr_roll;
public:
Students (size_t a){
arr_roll = new int(a);
}
~Students(){
std::cout<<"Destructor called"<<std::endl;
//delete arr_roll;
}
int & operator [] (size_t t){
return arr_roll[t];
}
};
int main(){
std::vector<Students> School(10,5);
School[0][1] = 2;
std::cout<< "School[0][1]: " << School[0][1]<<std::endl;
return 0;
}
I have a code like above and I am compiling it with gcc 9.5.0 . The output I am getting is as follows
**Destructor called**
School[0][1]: 2
Destructor called
Destructor called
Destructor called
Destructor called
Destructor called
Destructor called
Destructor called
Destructor called
Destructor called
Destructor called
Can anybody please explain why the destructor is being called during the creation of the vector (The 1st print ** marked)
The statement
first creates an object of type
Studentsusing the parameterized ctorStudents(size_t)and then uses the implicitly generated copy constructorStudents(const Students&)to create10copies of that object. So there are total 11 objects constructed(1 using parameterized ctor and other using copy ctor). Then at the time ofSchool's destruction, all elements are destructed using the destructor and we get the destructor called output.This all happens because the ctor
(3)given at std::vector is used here:You can verify this by adding a user defined copy ctor as done in this demo.
Note that first the parameterized ctor
Students(size_t)is implicitly used to create an object ofStudentstype and then the copy ctor is used to create 10 copies.