this is because the compiler generated c-ctor is being executed during the map accessing using l-value index operator.
check this code
struct stStruct
{
int some_value;
stStruct()
{
some_value = 10;
printf("\nCame in stStruct c'tor");
}
stStruct(const stStruct& oOrg)
{
some_value = oOrg.some_value;
printf("\nCame in stStruct copy c'tor");
}
~stStruct()
{
some_value -= 10;
printf("\nCame in stStruct d'tor");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
// Map of <int, struct>
std::map<int, stStruct> MyIntStructMap;
MyIntStructMap[0]; // stStruct c'tor will be called once and d'tor will be called twice
MyIntStructMap[0]; // stStruct c'tor or d'tor won't be called
printf("\nValue of some_value in stStruct %d", MyIntStructMap[0].some_value); // As d'tor was called twice, ideall it should print value -10
return 0;
}
generates:
Came in stStruct c'tor
Came in stStruct copy c'tor
Came in stStruct copy c'tor
Came in stStruct d'tor
Came in stStruct d'tor
Value of some_value in stStruct 10