I had a certain class in my program which I used to draw various shapes and to add events to shapes as well.
vector<XQuad*> _inputMappedShape;
void addRegularShape(Container inputPoints, Container outputPoints){
XQuad quad;
setInputPoints(quad, somePoints);
setInputPoints(quad, somePoints);
setArrowHandles(quad, somePoints);
_inputMappedShape[currentIndex++] = &quad;
}
XQuad* getMappedShape(int index){
return _inputMappedShape[index];
}
void setInputPoints(XQuad& quad, Point* somePoints);
void setOutputPoints(XQuad& quad, Point* somePoint);
void setArrowHandles(XQuad& quad, Point* somePoint);
Notice that in the above code (in method addRegularshape), I am passing quad by reference to other methods before adding it to the vector collection.
In my main program, I was trying to retrieve the shape using the getMappedShape method which would return a pointer to the quad for my purpose.
XQuad* returnedShape = getMappedShape(0)
I checked the memory address of quad allocated in addRegularShape method and the address being returned by the pointer (from method getMappedShape) and the memory addresses were the same.
However, somehow the data inside my XQuad class when returned from the getMappedShape was not correct (i.e. not the one which was modified in XQuad reference object in the other three member functions) and instead had some garbage values. I could not find a reason as to why it was happening and with suspicion to the memory getting corrupted or something, I changed the reference object in the addRegularShape to pointer as follows.
XQuad* quad = new XQuad();
Following this, the program started returning correct values but I am still in a little bit of doubt as to why it was happening? Wasn't adding the XQuad object the correct way of adding the addresses to the collection? Or is there some scope issue here i.e when the method goes out of scope, the object is destroyed and what I actually return from the collection has now become a garbage value?
_inputMappedShape[currentIndex++] = &quad;
Means you are assigning address of quad to _inputMappedShape. so you will get this address in your complete program.. but at the end of function addRegularShape(...) data associated with quad object will be destroyed as its scope will be over.. and _inputMappedShape will remain with address of quad which has no data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With