Qt signal and slots: are reference arguments copied?

余生长醉 提交于 2020-01-23 02:15:30

问题


In qt framework, most library signals and slots use pointers as parameters. I was wondering, If I create a signal-slot "structure" that takes a reference as the parameter instead of the pointer, will the whole parameter be copied, or just 4 bytes (32-bit system) like in a regular c++ reference?

I am asking this because I noticed something when I create a signal/ slot methods with the reference parameter. When I then connect them, the autocomplete mechanism in QTCreator doesn't hint me with reference parameters like he would do with pointer parameters. He hints me with the regular parameter. For example:

I create a signal and slot:

...
signals:
     void mySignal(int& parameter);
private slots:
     void on_mySignal(int& parameter);

I then attempt to connected them and Qt doesnt add & for reference in parameter:

...
connect(this, SIGNAL(mySignal(int)), this, SLOT(on_mySignal(int)));

I have to manually change to:

connect(this, SIGNAL(mySignal(int&)), this, SLOT(on_mySignal(int&)));

Thus I am wondering, does reference even work with signal/slot? I would appreciate all help.


回答1:


If you send and receive a reference, on the same thread, per default no copy will be made. If you do anything else, including sending/receiving a value or sending a reference to another thread, one, two or even three copies will be made.

What happens depends on the connection type and the assurances QT needs to know that references remain valid through the call. A direct connection on the same thread resolves to a simple function call, so very little can happen to the underlying data. A queued connection, however, offers no guarantees for when the call will actually happen, therefore QT will make copies to preserve data integrity. QT implicitly queues signals crossing thread boundaries.

If either side is pass-by-value then QT copies the data to not affect the underlying object's state.

For more information, have a look at this blog post.



来源:https://stackoverflow.com/questions/42187235/qt-signal-and-slots-are-reference-arguments-copied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!