我读到 qt 中的信号/槽概念应该始终按值而不是引用传递参数,以确保信号/槽在线程之间完美工作。
我现在有一段代码,只有当信号的参数是通过引用而不是值发出时才会编译:
#include <QObject>
class mythirdclass {
public:
mythirdclass();
};
class mysecondclass : public QObject, public mythirdclass {
public:
mysecondclass(mythirdclass third);
};
class myclass : public QObject {
Q_OBJECT
public:
myclass();
signals:
// not working
void messageReceived(mysecondclass mymessage);
// working
// void messageReceived(mysecondclass &mymessage);
};
myclass::myclass()
{
mythirdclass third;
mysecondclass msg(third);
emit messageReceived(msg);
}
mysecondclass::mysecondclass(mythirdclass third)
{
// DO stuff
}
mythirdclass::mythirdclass()
{
}
编译器错误是:
..\example\main.cpp: In constructor 'myclass::myclass()':
..\example\main.cpp:28:20: error: use of deleted function 'mysecondclass::mysecondclass(const mysecondclass&)'
emit signal(second);
^
..\example\main.cpp:8:7: note: 'mysecondclass::mysecondclass(const mysecondclass&)' is implicitly deleted because the default definition would be ill-formed:
class mysecondclass : QObject, public mythirdclass {
^
基于错误,我考虑为 mysecondclass
编写一个复制构造函数,但是经过一些尝试后,我暂时放弃了,因为我没有得到正确的结果。
所以我的问题是:
- 为什么编译失败?
- 如果由于缺少复制构造函数而失败,为什么编译器无法隐式定义复制构造函数?
- 在我的例子中,工作复制构造函数是什么样子的?
提前致谢。
最佳答案
Why is the compiling failing in the first place?
因为按值传递意味着复制,并且如果复制构造函数被删除,那么它根本无法按值传递,并且您的函数无法使用此签名进行编译,但它可以通过引用接收其参数,因为它不'不涉及复制。
If it fails because of a missing copy constructor, why is the compiler not able to define one implicitly?
它实际上失败了,因为它无法隐式定义一个。原因是您的类派生自QObject
。还有那个 QObject doesn't have a public or protected copy-constructor ,按设计。因此编译器无法隐式定义一个。
How would the working copy constructor in my case look like?
鉴于 QObject
的性质,以及当涉及到 QObject
不可复制时其背后的设计决策,我建议不要使用以下信号和槽:通过值(或者任何执行此操作的函数,信号/槽主要是深层函数)获取 QObject 或从其派生的类,而不是通过引用或指针。
关于c++ - 如何使 Qt Signal 按值发出而不是引用而不会出现编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431128/