编辑:这个答案是对原始问题的回应,该问题没有使用QObject
但class A
作为一个独立的类没有继承任何内容。后来对该问题进行了编辑,使该答案已过时,但我将把它留在这里以显示如果不使用QObject
.
唯一可以做到这一点的方法是让对象保持活动状态,直到计时器触发。例如:
class A : enable_shared_from_this<A> {
void fun() {
QTimer::singleShot(10, bind(&A::timerSlot, shared_from_this()));
}
public:
void timerSlot();
}
auto a = SharedPointer<A>(new A);
a->fun();
a->reset(); // a goes out of scope, but its referent is kept alive by the `QTimer`.
上述工作的原因是您class A
在设置计时器时捕获了 shared_ptr ,并且计时器将保留它(否则它无法触发)。
如果您不喜欢或不能使用最近的 C++ 功能或 Boost:
struct Functor {
Functor(SharedPointer<A> a) : _a(a) {}
void operator() { a->timerSlot(); }
SharedPointer _a;
};
class A {
void fun(shared_ptr<A> self) {
QTimer::singleShot(10, Functor(self));
}
public:
void timerSlot();
}
auto a = SharedPointer<A>(new A);
a->fun(a);