vector of Objects having pointer of Object

112 views Asked by At

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?

2

There are 2 answers

0
Shoe On

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 of Object (not to mention the fast-ticket to UB-land when dereferencing an uninitialized pointer). Here's the fixed code:

{
    Object myObject;
    std::vector<Object> stack;


    stuffHappensInObject(myObject);
    stack.push_back(myObject);

    if(IclickLoadLast){
        myObject = stack.at(stack.size() - 1);
    }
}

I've also changed size to stack.size() which is a valid method of std::vector that you can use. Also, take a look at std::stack which provides more stack-like operations:

{
    Object myObject;
    std::stack stack;


    stuffHappensInObject(myObject);
    stack.push(myObject);

    if(IclickLoadLast){
        myObject = stack.top();
    }
}

In both cases, if you are using C++11, I suggest you to use std::vector::emplace_back or std::stack::emplace instead of push_back and push.

1
Martin York On

Couple of issues:

This will not work:

stack.push_back(myObject);

because myObject has a type of Object* while the stack takes of objects of type Object. Please notice the slight difference in type. I am not sure why you are even using pointers (not enough context).

But there is another major problem:
Here you de-reference an uninitialized pointer. The result is undefined behavior.

Object* myObject;                  // No value defined (so it is random)
stuffHappensInObject(*myObject);   // De-referencing (the *) on an uninitialized pointer.