I have a class polymer with a static int count.
When I create a new polymer to add to an array of pointers I am using the count to find the correct location in the array and then I update the count in the constructor. While compiling in Windows it worked. However, when compiling in Linux (Ubuntu) it crashes unless I remove the updating of the count out of the constructor.
WORKS in Windows and Ubuntu:
polymerPointer[polymer::count] = new polymer();
polymer::count++;
WHEN the constructor doesn’t update the static variable (see below)
polymer::polymer(){
//sets up lots of variables but doesn't update the static member
};
CRASHES in Ubuntu (works in Windows):
polymerPointer[polymer::count] = new polymer();
WHEN the constructor does update the static variable (see below)
polymer::polymer(){
//sets up lots of variables and then updates the static member
count++;
};
I can rewrite the code, but I liked not having to remember to update the variable separately, which is why I put the update in the constructor. Any ideas on what is going wrong?
You’re hitting undefined behavior.
The following:
is not equivalent to
where
polymer()incrementspolymer::count.The undefined behavior results from the fact that you’re modifying a value and using that value in the same statement:
What probably is occuring is that the count is incremented and then the object is placed in that new position in the array. Now code will access the empty spot left as though it held a valid pointer, or when you get to the end of an array you may try to place the pointer out of the bounds of the array.
It’s bad design to put the count increment in a different place than where you actually insert into the array. What you should do is write a static member function that adds elements to the array and updates the count, and then use that instead of manually creating the object and manually placing it in the array, while expecting the count to get updated automatically.
Even better would be to just use a
vectorand have it manage it’s own count: