1
votes

I have a test application for a assignment where I have to push_back a shared pointer into a vector of shared pointers. However it is crashing on the push_back and I am not sure why.

I tried moving the shared_ptr instead of copying it to the vector and am still seeing the same issue. I tried to debug the issue, but for some reason the variables are not showing up in the debugger after I click on them (possible IDE issue). I did see a similar issue on stack overflow, but this is not the same issue as the shared pointer is being initialized before the push_back is called.

//Fill - will loop through and ask the user what elements to add
void fill(std::vector<std::shared_ptr<Test>> &vec, int num)
{
    for(int i {1}; i <= num; i++)
    {
        std::cout << "Enter data pointer [" << i << "] : ";
        int data {};
        std::cin >> data;
        std::shared_ptr<Test> data_ptr = std::make_shared<Test> (data);
        std::cout << "Created shared pointer for " << data_ptr->get_data() << 
        std::endl; //debug
        vec.push_back(std::move(data_ptr));
        std::cout << "Added to vector" << data_ptr->get_data() << std::endl; 
        //debug (crash issue is with the pushback method)
    }
}

The program is crashing when after the shared_ptr is created and the push_back method doesn't appear to execute. I added cout debug messages to try and see where in this function the program is failing. the "created shared ptr" is called, but the "Added to vector" is not called.

1
What is Test? Also, what is get_data()? I don't see it as part of the std::shared_ptr API...BobMorane
Do you see this in your console? std::cout << "Created shared pointer for " << data_ptr->get_data() << std::endl;BobMorane
get_data() is returning the int that is stored as part of the Test class. I am seeing the "Created shared pointer for" cout text.Nyrathalnian

1 Answers

0
votes

When you move from a shared_ptr the moved from variable is invalid (in this case null).

You call data_ptr->get_data() before pushing, which is fine. But after you push (via move) calling data_ptr->get_data() a second time will use the (now moved-from) smart pointer - hence your crash.