Thursday, August 16, 2018

c++ - std::pair and class destructors










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 my_map;

my_map.insert( std::make_pair (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!


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...