QT:使用移动语义将信号连接到插槽

时间:2017-10-02 08:10:24

标签: c++ qt c++11 move qt-signals

好的,我有这样的事情:

void EmailReceiverThread::foreachEmailAccount(ConfigEmailAccount account)
{
    Email email;
    EmailReader emailReader(account);
    while (emailReader.pollEmail(email))
    {
        writeEmailToDatabase(email);
    }
}

ForeachEmailAccount是EmailReceiverThread中的一个插槽。它是从run()方法调用的:

GetConfigEmailDAO* accountReader = new GetConfigEmailDAO(type, m_channel);
connect(accountReader, SIGNAL(emailAccount(ConfigEmailAccount)),
        this, SLOT(foreachEmailAccount(ConfigEmailAccount)), Qt::QueuedConnection);
DbThread::postAction(accountReader);

GetConfigEmailDAO执行查询,获取电子邮件帐户并执行emit:

emit emailAccount(account);

到目前为止这是有效的。问题是,我正在复制ConfigEmailAccount类。我想避免这种性能受到打击。所以,我的想法是使用c ++ 11移动语义发出帐号:

emit emailAccount(std::move(account));

我使用新语法重写了插槽和信号:

void foreachEmailAccount(ConfigEmailAccount&& account);

不幸的是,这不起作用。我有下一个编译错误:

moc_emailreceiverthread.cpp:88: error: cannot bind ‘ConfigEmailAccount’ lvalue to ‘ConfigEmailAccount&&’
     case 1: _t->foreachEmailAccount((*reinterpret_cast< ConfigEmailAccount(*)>(_a[1]))); break;

我能做什么?

这里的最小可验证示例:

#include <QCoreApplication>
#include <QObject>

class ConfigEmailAccount
{
    QString some_data;
};

class GetConfigEmailDAO : public QObject
{
    Q_OBJECT
public:
    void execute();

signals:
    void emailAccount(ConfigEmailAccount&& account);
};

void GetConfigEmailDAO::execute()
{
    ConfigEmailAccount account;
    emit emailAccount(std::move(account));
}

class EmailReceiverThread : public QObject
{
    Q_OBJECT
public:
    void execute();
public slots:
    void foreachEmailAccount(ConfigEmailAccount&& account);
};

void EmailReceiverThread::execute()
{

    GetConfigEmailDAO* accountReader = new GetConfigEmailDAO;
    connect(accountReader, SIGNAL(emailAccount(ConfigEmailAccount)),
            this, SLOT(foreachEmailAccount(ConfigEmailAccount)), Qt::QueuedConnection);
    accountReader->execute();
}

void EmailReceiverThread::foreachEmailAccount(ConfigEmailAccount&& account)
{

}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qRegisterMetaType<ConfigEmailAccount>("ConfigEmailAccount");
    EmailReceiverThread reader;
    reader.execute();
    return a.exec();
}

#include "main.moc"

1 个答案:

答案 0 :(得分:0)

最后,我采用了QT的浅层复制机制:
http://doc.qt.io/qt-5.6/qshareddatapointer.html#details