我正在使用std::map
' int'作为键和自定义结构作为值。当我访问密钥时,它会创建密钥和值(如预期的那样),但是值的一次调用会被调用一次,同时它会被调用两次。我发现它真的很奇怪。
示例:
struct stStruct
{
int some_value;
stStruct()
{
some_value = 10;
printf("\nCame in stStruct 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 ctor called once and dtor twice
MyIntStructMap[0]; // neither stStruct ctor nor dtor called
printf("\nValue of some_value in stStruct %d", MyIntStructMap[0].some_value);
// Expected -10 above as dtor was called twice
}
输出是:
Came in stStruct c'tor
Came in stStruct d'tor
Came in stStruct d'tor
Value of some_value in stStruct 10
这真令人沮丧。特别是如果在结构中有指针并分别在它的ctor和dtor中分配deallocate内存,则代码崩溃(因为同一指针的删除发生两次)。
此外,尽管代码some_value -= 10;
被调用了两次,我仍然不明白,上面示例中some_value
的值如何仍然是10
?
我在Windows上使用VS2010。
答案 0 :(得分:2)
这是因为在使用l值索引运算符进行地图访问期间正在执行编译器生成的c-ctor。
检查此代码
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;
}
产生
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