Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connect const QString& or const QString

Tags:

qt

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

void wigdetA::something()
{

//
//e.g
//
QTreeWidgetItem *it = this->treeWidget->currentItem();
if (it == 0)
    return;

QString s = it->text(1);

emit passToMainWindow(s);
}

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

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

or can I use const reference

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

Both ways work, but I though the second const& will crash the appliaction since QString s is local and it will be destroyed when the function something() exits.

or I'm missing something ?

like image 535
krusty Avatar asked Oct 22 '22 20:10

krusty


1 Answers

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

However it is always better to pass it by value, especially if connection is made between objects residing in different threads. QString uses implicit sharing (aka copy-on-write), so it does not cost much to pass it by value.

like image 198
Archie Avatar answered Oct 27 '22 08:10

Archie