Quick question guys, I have the following issue:
I have an Object (struct) pointer in my code, and when I modify something, to keep track of its history, I'm saving it in a vector (stack) of Objects. So I'm trying to do.
{
Object* myObject;
vector<Object> stack;
stuffHappensInObject(*myObject);
stack.push_back(myObject);
if(IclickLoadLast){
myObject = stack.at(size-1);
}
}
I'm having a problem with the push_back call and I don't know if its possible to get ALL the struct variables in a new Object into the stack. How can I do that?
Don't use pointers in the first place, there is not need here. The problem was caused by the fact that you were trying to add a
Object*to a vector ofObject(not to mention the fast-ticket to UB-land when dereferencing an uninitialized pointer). Here's the fixed code:I've also changed
sizetostack.size()which is a valid method ofstd::vectorthat you can use. Also, take a look atstd::stackwhich provides more stack-like operations:In both cases, if you are using C++11, I suggest you to use
std::vector::emplace_backorstd::stack::emplaceinstead ofpush_backandpush.