I was initiating new object on same local variable multiple times. From my test it seems I have some misunderstanding regarding destructor calling sequence.
So, here is the test code. I am initiating object of type A 3 times on variable obj. I was curious if destructor will be called as obj is not going out of scope. My idea was it will be called and another constructor will be called. So, the sequence will be like this
1st init constructor-> 1st initiated object destructor -> 2nd init constructor-> 2nd initiated object destructor -> 3rd init constructor-> 3rd initiated object destructor
But it seems this is not the case. I have printed the memory location of created/destroyed object when calling constructor and destructor. Also it seems multiple init creates object on stack without reference.
So, here is my code,
#include <iostream>
class A{
public:
A()
{
std::cout<<"constructing object at "<<this<<std::endl;
}
~A()
{
std::cout<<"destructing object at "<<this<<std::endl;
}
};
int main()
{
A obj = A();
obj = A();
obj = A();
return 0;
}
Here is one output. Other runs have produced similar result with different pointer value.
constructing object at 0x7ffed4e26465
constructing object at 0x7ffed4e26466
destructing object at 0x7ffed4e26466
constructing object at 0x7ffed4e26467
destructing object at 0x7ffed4e26467
destructing object at 0x7ffed4e26465
So, here are my questions.
- local object variable resides on stack. Am I correct?
- Why 1st init object is destroyed at last but others created and destroyed sequentially. Is there any error in my findings?
- If in (2) answer is there is error, what is the sequence of constructor and destructor calling in case of multiple initialization of same variable?
I am using g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0