I ran into a thread/memory problem recently while developing a Qt based appication in c++ and I am looking for a correct explanation. I can't really post a fully functioning example as that would require linking to Qt etc. But the problem is pretty clearly explained in a few short lines.
When I click a button on the gui, something like this happens:
void MainWindow::onClick(){
std::vector<int> vec;
vec.push_back(0);
dev.connect(vec);
// do some more stuff
}
In this instance, dev
is a member of MainWindow
and is of class type Device
which represents hardware (or more accurately, hardware drivers) that I want to connect with. The code for connect
is something like:
void Device::connect(const std::vector<int>& vec){
// do some stuff with vec that takes a long time
}
The problem that I had was that the device drivers were throwing me exceptions because they were getting bad values out of vec
. And indeed, when I would break into connect
, the data was gone: in that scope vec
was empty memory. I fixed the problem by using shared_ptr
s.
My theory is that when I call dev.connect(vec)
from the GUI thread, Qt actually puts that call on a separate thread. Then, that function takes a long time and Qt decides that it is time to go on and complete onClick
(or something like that, maybe it happens immediately) so that by the time vec
gets handled in Device::connect
, it was already out of scope. This fits given the fact that shared_ptr
saves the day here.
So my questions are, am I right about this? and can someone explain the details of Qt's implicit threading behavior or else point to some such explanation?