在以结构为值的STL映射中,结构的析构函数被调用两次

In STL map with structure as value, destructor of the structure gets called twice

本文关键字:结构 调用 两次 析构函数 STL 映射      更新时间:2023-10-16

我有一个std::map与'int'作为关键和自定义结构体作为值。当我访问一个键时,它创建键和值(如预期的那样),但值的tor被调用一次,同时它的tor被调用两次。我发现这真的很奇怪。

的例子:

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 ?

这是因为编译器生成的c-ctor是在使用l值索引操作符访问映射时执行的。

检查此代码

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