const-ref当在Qt中发送信号时 [英] const-ref when sending signals in Qt

查看:438
本文介绍了const-ref当在Qt中发送信号时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个我从来没有得到过const-ref,我真的希望有人可以解释它给我。

This is a thing that I never quite got with const-ref and I really hope that someone could explain it to me.

当调用另一个函数函数,我得到的const-ref是传递堆栈对象,我不打算篡改的最好的方法。例如:

When calling a function inside of another function, I get that const-ref is the best way when passing stack objects that I don't plan to tamper with. For example:

void someInnerFunction(const QString& text) {
    qDebug() << text;
}

void someFunction() {
    QString test = "lala";
    ....
    someInnerFunction(test);
}

到目前为止很好,我猜。但是信号呢?是不是有任何风险自带传递一个参考?即使它是 const 。感觉就像我一直在读所有的关于const-ref的文档,但我仍然发现有点冒险,因为我理解它是发送一个对象的引用,并保持它 const 。如果它所指的对象超出范围怎么办?

So far so good, I guess. But what about signals? Isn't there any risk that comes with passing a reference? Even though it's const. It feels like I've been reading all the docs about const-ref but I still find a bit risky since I understand it as "sending a reference to an object and keeping it const". What if the object it's referring to goes out of scope?

例如:

void someFunction() {
    connect(this, SIGNAL(someSignal(const QString&)), this, SLOT(someSlot(const QString&)));

    QString test = "lala";
    emit someSignal(test);

    // doesnt test go out of scope here? and since im not using queued connection the QString object doesnt get copied. 
}

void someSlot(const QString& test) {
    qDebug() << test; // will this work?
}

这里真正发生了什么?我经常使用const-ref函数调用,我只想访问对象,但不改变它。但是信号呢?大多数信号似乎在Qt文档中有const-ref parm,但它是如何工作的?

What is really happening here? I frequently use const-ref on function calls where I just want to access the object but not change it. But what about signals? Most signals seems to have const-ref parm in the Qt doc, but how does it work?

推荐答案

根据这个答案,Qt只是替换const

According to this answer, Qt just replaces const references with copies.

编辑:显然不总是这样...我只是做了一个基本的测试程序与一个线程,并且引用正确传递。它的常数也保持不变。无论如何,是的,你需要警惕的变量超出范围,加上你不能通过线程发送引用这种方式。

Apparently not always the case... I just did a basic test program with one thread, and the reference was passed correctly. Its const-ness remained intact, as well. Anyways, yes, you do need to be wary of the variable going out of scope, plus you can't send references across threads this way. If you do, only copies will be passed.

要回答您的示例的注释中的问题,是的,它将工作,不管它是直接连接还是排队连接。如果它是一个直接连接,它将工作,因为 someSlot()将在 someFunction()如果它是一个排队的连接,它会工作,因为 test 将被复制,而不是通过引用传递。

To answer the questions in the comments of your example, yes, it will work regardless of whether it's a direct or queued connection. If it's a direct connection, it will work because someSlot() will be executed before someFunction() finishes; if it's a queued connection, it will work because test will be copied instead of passed by reference.

这篇关于const-ref当在Qt中发送信号时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆