I have a class that I want to contain multiple objects of something I created. Right now the code that works is:
process.h:
private:
myObj *data;
process.cc:
data = new myObj[10];
I would like to pass a value to the constructor however, so I tried to convert it to a std::vector (after modifying constructor to take a value).
process.h:
private:
std::vector<myObj> data;
process.cc:
for (int m=0; m<10; m++) data.push_back( myObj(1.2) );
When I try that it crashes upon execution with
*** glibc detected *** ... corrupted double-linked list: ... ***
And the backtrace in gdb shows an error in the destructor when I tried to free some memory for other arrays I allocated. A search didn’t show up anything that was obvious. I am using a few static member variables in myObj, could that be an issue?
You are experiencing a double deletion bug. Consider this simple example:
The temporary object that is pushed onto
datais stored properly. However, since it is a temporary, it is destroyed right after the push. This means, thepmember is deleted when the temporary is destroyed, so the vector’s version of the copy has a dangling pointer. When the vector object is destroyed, the pointer will be deleted again, resulting in a corrupted heap. The error message you received was from theglibccode complaining about the resulting bad state.To fix this problem, a proper copy constructor should be defined, to pass ownership of the objects from the temporary to the destination. The rule of three says we should define the assignment operator as well.
The use of mutable is required to be able to modify the
pmember when the instance isconst, andconstwas needed because temporaries are being passed in to the copy constructor. With this change, pushing items into the vector work fine.A better solution would be to define
pto use aunique_ptrinstead.No destructor is needed in this example, since the default destructor will destruct p, which will cause the
Otherinstance to be deleted byunique_ptr.