std::pair and class destructors
Possible Duplicate:
What is The Rule of Three?
How exactly does std::pair
call destructors for its components? I am trying to add instances of a class to an std::map
, but I am getting errors regarding the destructor of my class.
I have narrowed down my question/problem to the following extremely simple example.
Below, my_class
merely creates an int
array at construction, and deletes it at destruction. Somehow I am getting a "double delete" error:
//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
Meanwhile, over in 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
Compilation goes fine, but this generates the following runtime error:
*** glibc detected *** ./experimental_code: double free or corruption (fasttop):
Or, with 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)
(line numbers are off because I cut out comments and stuff)
I must be missing something about std::pair
...?
Thanks to all in advance!
When you add my_class
to stl containers the copy constructor is called. As you don't define one it does a memberwise copy and two my_class
objects are created that point to the same int array, When these are deleted the same int array might be deleted twice
Please take a look at Rule of three
In C++11 also look at move constructor if you are worried about the efficiency.
Your class violates the rule of three by defining a destructor without a copy constructor and an assignment operator. Once you define these, your code should run OK: STL containers rely heavily on these, so you should ask yourself if you've implemented all three every time you use a class as a template argument for an STL container.
你必须定义一个合适的拷贝构造函数,因为你的类的拷贝通过指针的复制实例共享同一个数组。
链接地址: http://www.djcxy.com/p/73172.html上一篇: back()内存双倍空闲
下一篇: std :: pair和类的析构函数