Connect const QString & or const QString

what's the correct way to emit a signal with a QString if that QString is local. I mean, I have such a function in wigdetA

void wigdetA::something() { // //eg // QTreeWidgetItem *it = this->treeWidget->currentItem(); if (it == 0) return; QString s = it->text(1); emit passToMainWindow(s); } 

Should I create a connection like this (just const QString):

  connect(wigdetA, SIGNAL(passToMainWindow(const QString)), this, SLOT(passToMainWindow(const QString))); 

or i can use a constant link

 connect(wigdetA, SIGNAL(passToMainWindow(const QString&)), this, SLOT(passToMainWindow(const QString&))); 

Both methods work, but I, although the second const & will cause the application to crash, since QString s is local, and it will be destroyed when the something () function exits.

or am I missing something?

+4
source share
2 answers

Since the emitting and receiving objects are in the main stream, Qt uses a direct connection (the slot is called immediately as you emit). In this case, your local string is still on the stack.

However, it is always better to pass it by value, especially if the connection is made between objects living in different threads. QString uses implicit sharing (aka copy-on-write), so it’s not expensive to pass it by value.

+1
source

emit passToMainWindow(s) will call the slot in the main window when it is emitted. so it will not matter. when working with qt slots, they mainly use const QString& , so I assume that the structure will make sure that the line is not deleted before it was used by the slot.

0
source

All Articles