編輯:這個答案是迴應原來的問題,沒有使用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`.
究其原因,上述工作是你捕捉一個shared_ptr來class A
設置定時器時,定時器將守住它(否則無法點火)。
如果你不喜歡或者不能使用最近的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);
請刪除「粗碼」,並添加*確切*代碼在那裏。在一個測試案例中,魔鬼在細節中...... – peppe