We are passing the object to another thread. It suppose to be deleted when oops2 () function is out of scope. How is it possible that after deleting data object we do not have crash in another thread and another thread is successfully working with that object?
class Data {
public:
Data(int val = 0) {}
int getVal () const { return mVal; }
void setVal(int val) { mVal = val; }
protected:
int mVal;
};
void set_val(int& i, Data* data)
{
data->setVal(i);
}
void print_val(Data* data)
{
cout << "Data value = " << data->getVal() << endl;
}
struct func2
{
Data* data;
func2(Data* data_): data(data_){}
void operator()()
{
printf("Address of func2 data is %p\n", data);
for (int j=0;j < 1000000;++j)
{
print_val(data);
set_val(j, data);
}
}
};
void oops2()
{
Data* data = new Data(100);
func2 my_func(data);
my_thread = std::thread(my_func);
delete data;
}
int main()
{
oops2();
my_thread.join();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire