cmo*_*cmo 1 c++ destructor map std-pair
可能重复:
三个规则是什么?
如何std::pair为其组件调用析构函数?我正在尝试将类的实例添加到a std::map,但是我的类的析构函数出错了.
我已经将我的问题/问题缩小到以下非常简单的例子.
下面,my_class仅int在构造时创建一个数组,并在销毁时删除它.不知何故,我得到一个"双删除"错误:
//my_class.h
class my_class {
public:
int an_int;
int *array;
//constructors:
my_class()
{
array = new int[2];
}
my_class(int new_int) : an_int(new_int)
{
array = new int[2];
}
//destructor:
~my_class()
{
delete[] array;
}
}; //end of my_class
Run Code Online (Sandbox Code Playgroud)
与此同时,在main.cpp ...
//main.cpp
int main(int argc, char* argv[])
{
std::map<int, my_class> my_map;
my_map.insert( std::make_pair<int, my_class> (1, my_class(71) ) );
return 0;
} // end main
Run Code Online (Sandbox Code Playgroud)
编译很顺利,但这会产生以下运行时错误:
*** glibc detected *** ./experimental_code: double free or corruption (fasttop):
Run Code Online (Sandbox Code Playgroud)
或者,与valgrind:
==15258== Invalid free() / delete / delete[] / realloc()
==15258== at 0x40249D7: operator delete[](void*) (vg_replace_malloc.c:490)
==15258== by 0x8048B99: main (my_class.h:38)
==15258== Address 0x42d6028 is 0 bytes inside a block of size 8 free'd
==15258== at 0x40249D7: operator delete[](void*) (vg_replace_malloc.c:490)
==15258== by 0x8048B91: main (my_class.h:38)
Run Code Online (Sandbox Code Playgroud)
(行号被关闭,因为我删除了评论和内容)
我一定错过了std::pair......?
感谢所有提前!