连接const QString&或const QString

kru*_*sty 5 qt

如果QString是本地的,用QString发出信号的正确方法是什么?我的意思是我在wigdetA中具有这样的功能

void wigdetA::something()
{

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

QString s = it->text(1);

emit passToMainWindow(s);
}
Run Code Online (Sandbox Code Playgroud)

我应该像这样创建连接(只是const QString):

 connect(wigdetA, SIGNAL(passToMainWindow(const QString)), this, SLOT(passToMainWindow(const QString)));
Run Code Online (Sandbox Code Playgroud)

或者我可以使用const reference

connect(wigdetA, SIGNAL(passToMainWindow(const QString&)), this, SLOT(passToMainWindow(const QString&)));
Run Code Online (Sandbox Code Playgroud)

两种方法都可以,但是我第二个const&会使应用程序崩溃,因为QString是本地的,并且在退出something()函数时会销毁它。

还是我想念什么?

Arc*_*hie 2

由于发送和接收对象都在主线程中,因此 Qt 使用直接连接(在发送时立即调用槽)。在这种情况下,您的本地字符串仍在堆栈中。

但是,最好按值传递它,尤其是在驻留在不同线程中的对象之间建立连接时。QString 使用隐式共享(又名写时复制),因此按值传递它的成本并不高。

  • 这是错误的。跨线程信号是排队的(参见 Qt::QueuedConnection),因此在每种情况下都会复制值,并且使用 const 引用是安全的。因此,人们始终可以安全地使用 const 引用。 (3认同)