在以结构为值的STL映射中,结构的析构函数被调用两次
In STL map with structure as value, destructor of the structure gets called twice
我有一个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
相关文章:
- 没有为自己的结构调用列表推回方法
- 调用 C 文件中的"C++"结构
- C++结构默认调用值
- 在结构外部调用指向函数的指针
- C++结构到德尔福记录dll调用
- C++:对象将 lambda 存储到结构中,稍后调用该函数
- C++ 结构错误"调用'erase'没有匹配函数
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- QT C++,从子层次结构调用 main 中的函数
- 为在与类方法中的类相同的命名空间中定义的结构调用重载运算符
- Eclipse Neon.3 更改类型层次结构/调用层次结构中的颜色
- 使用C#的结构调用C 代码
- 从嵌套结构调用受保护的基类函数
- 使用Node.js中包含char数组的结构调用C++dll
- 节点结构调用自身
- 如何使用结构调用函数 (C++)
- 何时为此结构调用复制构造函数
- 通过结构调用递归函数
- 返回的结构调用它自己的析构函数,用于销毁分配的对象