Possible Duplicate:
What is The Rule of Three?的std ::对,类析构函数
为什么说std::pair
调用析构函数及其组成部分?我正在尝试将一个类的实例添加到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
同时,比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
编译去罚款,但这种生成以下运行时错误:
*** glibc detected *** ./experimental_code: double free or corruption (fasttop):
或者,用的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)
(行号已关闭,因为我删除了评论和内容)
我必须缺少一些关于std::pair
...?
感谢所有提前!
为什么不使用'int array [2]'而不是'int * array'? – Pubby 2012-01-17 15:31:11
那么,[你的拷贝构造函数和拷贝赋值操作符在哪里?](http://stackoverflow.com/q/4172722/500104) – Xeo 2012-01-17 15:31:12
请注意,如果你不需要拷贝构造函数或拷贝赋值操作符直接分配内存。改为使用'std :: vector an_array'。 –
2012-01-17 15:36:27