mercredi 23 septembre 2020

Is it safe to use std::vector

I have a problem when using std::vector<std::shared_ptr<MyType>>.

I have two threads and they share one data: std::shared_ptr<std::vector<std::shared_ptr<MyType>>> my_object_vec_ptr;

In thread 1:

//loop
while(true)
{
    std::shared_ptr<MyType> my_object_ptr = std::make_shared<MyType>(...);

    /*lock my_data_mutex*/
    my_object_vec_ptr->push_back(my_object_ptr);
    /*unlock*/
}

In thread 2:

while(true)
{
    /*lock mutex*/
    print my_object_vec_ptr; //pseudo code, just print the data
    /*unlock*/
}

I found the output from thread 2 just crashed. The content is changed.

I guess it is because my_object_vec_ptr->push_back(something) caused memory reallocation and makes the shared pointers released.

Is it correct? Is it safe to use std::vector<std::shared_ptr<MyType>> ?

Aucun commentaire:

Enregistrer un commentaire