Search code examples
c++classpointersvectormember

Vector member is lost while managing a queue of the class pointers C++


I have a very simple class called AClass with two members: an int and a vector of ints. In my program, I'm trying to use a queue of pointers to objects of that class and a while loop on that queue until it is empty. Within that while loop, I sometimes create new objects and add them to the queue for some processing. The problem I'm encountering is that the vector member seems to be lost for the objects created within that loop. The int member is accessible though. I can't quite figure out why...

Here's a small example of code that illustrates my problem.

#include <iostream>
#include <vector>
#include <queue>
#include <string>


class AClass
{
public:
    int a_number;

    std::vector<int> a_vector;

    void print()
    {
        std::cout << "a number: " << a_number << std::endl;
        std::cout << "a vector: ";

        for (size_t i = 0; i < a_vector.size(); i++)
        {
            std::cout << a_vector[i] << "  ";
        }
        std::cout << std::endl;
    }
};


int main()
{
    std::queue <AClass*> aclass_pointers_queue;

    AClass first_aclass_object;
    first_aclass_object.a_number = 2;
    first_aclass_object.a_vector = { 1,2,3,4,5 };

    aclass_pointers_queue.push(&first_aclass_object);

    int some_break_condition = 1;

    while (!aclass_pointers_queue.empty())
    {
        AClass* current_class_object = aclass_pointers_queue.front();
        current_class_object->print();
        aclass_pointers_queue.pop();

        AClass another_aclass_object;
        another_aclass_object.a_number = 3;
        another_aclass_object.a_vector = { 5,4,3,2,1 };

        aclass_pointers_queue.push(&another_aclass_object);

        if (some_break_condition >= 2)
        {
            break;
        }
        some_break_condition++;
    }

    return 0;
}

Here's the output:

a number: 2
a vector: 1  2  3  4  5
a number: 3
a vector:

Nothing is printed out for the vector of the object created in the while loop. It's size is zero.


Solution

  • Inside the while loop, you are adding pointers to the queue, that point to the address of a local variable. In the next iteration of the loop, that variable dies, and the pointer that you have is no longer valid.

    The first pointer that you add to the queue is the address of an object that lives for the duration of main, so that pointer is valid.

    You could allocate memory for the pointers that you add to the queue. But you should prefer using something like std::unique_ptr, instead of raw pointers, if you choose to go that route.