lundi 2 octobre 2017

QT: Connect signals to slots with move semantics

Ok, i have something like this:

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

ForeachEmailAccount is a slot in EmailReceiverThread. It's called from the run() method:

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

GetConfigEmailDAO does a query, fetch the email account and do the emit:

emit emailAccount(account);

This works so far. The problem is, i'm copying the class ConfigEmailAccount. I would like avoid that perfomance hit.

So, my idea is emit the account using c++11 move semantics: emit emailAccount(std::move(account));

I rewrited the slots and signals with the new syntax:

void foreachEmailAccount(ConfigEmailAccount&& account);

Unfortunaly, this doesn't work. I have the next compilation error:

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

What could i do?

Minimal verifiable example here:

#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"

Aucun commentaire:

Enregistrer un commentaire