I have the following program where I test the order of constructor and destructor calls and I was surprised by the output.
#include <iostream>
#include <utility>
class Doctor {
public:
Doctor(){
std::cout << "Doctor Creation\n";
}
~Doctor(){
std::cout << "Doctor DeCreation\n";
}
};
class Nurse{
public:
int op = 0;
Nurse(){
std::cout << "Nurse Creation\n";
}
~Nurse(){
std::cout << "Nurse " << op << " DeCreation\n";
}
};
class Hospital{
private:
Doctor doc;
Nurse nurse;
public:
Hospital(){
std::cout << "Hospital Creation\n";
}
~Hospital(){
std::cout << "Hospital DeCreation\n";
}
void operate(){
std::cout << "Hospital Operation\n";
nurse.op++;
std::cout << &this->nurse << " " << nurse.op << "\n";
reset_hospital();
std::cout << &this->nurse << " " << nurse.op << "\n";
}
void reset_hospital(){
std::cout << &this->nurse << " " << nurse.op << "\n";
nurse = std::move(Nurse());
doc = std::move(Doctor());
}
};
int main(){
Hospital hospital;
hospital.operate();
}
https://godbolt.org/z/bf8KbqsTK
The output is:
Doctor Creation
Nurse Creation
Hospital Creation
Hospital Operation
0x7fff2316866c 1
0x7fff2316866c 1
Nurse Creation
Nurse 0 DeCreation
Doctor Creation
Doctor DeCreation
0x7fff2316866c 0
Hospital DeCreation
Nurse 0 DeCreation
Doctor DeCreation
Shouldn't it be Nurse 1 DeCreation
on the std::move operation? The current object is destroyed and replaced by the new one? Or for some reason, is it copying instead of moving?
I'm so confused.