c++ - Why does double free or corruption error not happen at run time for boost ptr_container? -
i testing out boost ptr_containers , wrote small program below:
class test { public: ~test() { cout << "test destructor called" << endl; } }; int main(int argc, char** argv) { boost::ptr_map<int, test> testcontainer; boost::ptr_vector<test> testvector; (int i=0; i<2; ++i) { test* ptr = new test(); testcontainer.insert(i, ptr); testvector.push_back(ptr); } }
once execute program, "test destructor called" printed 4 time , program completes successfully. expecting printing happen 2 times , "doube free..." error message thrown. why not happen in above case, happens raw pointer (test*)?
ptr_map
, ptr_vector
own elements.
the program incorrect. inserting same elements in 2 containers @ once leads double deletion.
the behaviour of delete on already-deleted pointer undefined. can happen. see undefined behaviour
use tool valgrind catch this.
in case did want know, easiest way fix sample using non-owning pointers 1 of containers. sure manage relative lifetimes of elements:
#include <boost/ptr_container/ptr_vector.hpp> #include <iostream> #include <map> class test { public: ~test() { std::cout << "test destructor called" << std::endl; } }; int main() { boost::ptr_vector<test> testvector; { std::map<int, test*> testcontainer; (int i=0; i<2; ++i) { test* ptr = new test(); testcontainer.emplace(i, ptr); testvector.push_back(ptr); } } }
Comments
Post a Comment