可以使用以下代码吗?
class Test : public QObject
{
Q_OBJECT
signals:
void myQtSignal(const FooObject& obj);
public:
void sendSignal(const FooObject& fooStackObject)
{
emit myQtSignal(fooStackObject);
}
};
void f()
{
FooObject fooStackObject;
Test t;
t.sendSignal(fooStackObject);
}
int main()
{
f();
std::cin.ignore();
return 0;
}
由于信号/插槽连接的工作方式,传递Qt信号的参考并不危险:
emit MySignal(my_string)
直接返回所有直接连接的插槽。http://qt-project.org/doc/qt-5.1/qtcore/qt.html#ConnectionType-enum
可以看下这个测试:
#include <iostream>
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
class Param {
public:
Param () {}
Param (Param const &) {
std::cout << "Calling Copy Constructor\n";
}
};
class Test : public QObject {
Q_OBJECT
public:
Test () {
for (int index = 0; index < 3; index++)
connect(this, &Test::transmit, this, &Test::receive,
Qt::QueuedConnection);
}
void run() {
Param p;
std::cout << "transmitting with " << &p << " as parameter\n";
emit transmit(p);
QTimer::singleShot(200, qApp, &QCoreApplication::quit);
}
signals:
void transmit(Param const & p);
public slots:
void receive(Param const & p) {
std::cout << "receive called with " << &p << " as parameter\n";
}
};
还有
#include <QCoreApplication>
#include <QTimer>
#include "param.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// name "Param" must match type name for references to work (?)
qRegisterMetaType<Param>("Param");
Test t;
QTimer::singleShot(200, qApp, QCoreApplication::quit);
return a.exec();
}
运行
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
receive called with 0x1bbf7c0 as parameter
receive called with 0x1bbf8a0 as parameter
receive called with 0x1bbfa00 as parameter
尝试下这个
transmitting with 0x7ffebf241147 as parameter
receive called with 0x7ffebf241147 as parameter
receive called with 0x7ffebf241147 as parameter
receive called with 0x7ffebf241147 as parameter
如果转到按值传递:
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
Calling Copy Constructor
receive called with 0x7fff15146ecf as parameter
Calling Copy Constructor
receive called with 0x7fff15146ecf as parameter
Calling Copy Constructor
receive called with 0x7fff15146ecf as parameter