我想QtConcurrent::run()
用于成员函数,但似乎它不使用指向实例的指针。相反,它看起来像调用了默认构造函数
#include <QObject>
#include <QDebug>
#include <QtConcurrent>
class Foo : public QObject
{
Q_OBJECT
public:
Foo(int n = 0):n(n){}
Foo(const Foo & f):Foo(f.n){}
void foo(){qDebug() << "Foo " << n;}
void bar(){QtConcurrent::run(this, &Foo::foo);}
private:
int n;
};
void test(){
Foo foo = Foo(2);
foo.foo();
foo.bar();
QtConcurrent::run(&foo, &Foo::foo);
QtConcurrent::run(&foo, &Foo::bar);
}
运行的结果test()
是:
Foo 2
Foo 0 // Should be a 2
Foo 0 // Should be a 2
Foo 0 // Should be a 2
编辑:我的实例确实超出了范围。此代码工作正常
void test(){
Foo * foo = new Foo(2);
foo->foo();
foo->bar();
QtConcurrent::run(foo, &Foo::foo);
QtConcurrent::run(foo, &Foo::bar);
}