【发布时间】:2012-02-12 09:52:07
【问题描述】:
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)
(行号已关闭,因为我删掉了 cmets 和其他东西)
我一定是错过了std::pair...?
提前感谢大家!
【问题讨论】:
-
为什么不用
int array[2]而不是int *array? -
请注意,如果您不直接分配内存,则不需要复制构造函数或复制赋值运算符。请改用
std::vector<int> an_array。 -
@Xeo:在许多情况下,您可以更好地使用标准容器并省略您的复制构造函数和复制赋值。不要盲目地认为手写复制是最好的解决方案。
-
@phresnel:呃,谢谢,我知道。但是,如果您有一天需要玩这些位(或将
std::vector作为家庭作业),那么了解三法则是件好事。
标签: c++ map destructor std-pair