I have following code
#include <iostream>
#include <vector>
struct M {
int a = 0;
int b = 0;
~M(){}
};
std::vector<M> ms;
void met(int i)
{
// This struct 'm' does not get deleted after lifetime of function "met" is over
M m;
m.a = i;
m.b = i * i;
ms.push_back(m);
}
int main()
{
for(int i = 0; i < 10; i++){
met(i);
}
for(int i = 0; i < 10; i++){
std::cout << ms[i].a << " : " << ms[i].b << std::endl;
}
return 0;
}
// OUTPUT
0 : 0
1 : 1
2 : 4
3 : 9
4 : 16
5 : 25
6 : 36
7 : 49
8 : 64
9 : 81
As we know scope of local variable is lifetime of immediate code block. In above code, scope of struct M
is lifetime function met
. But in above code works fine as we can see output given below code. I was expecting undefined behavior Cause M m
has to be deleted once function met return to main. Is is anything special about struct in this case?