关于QTimer::singleShot的一个奇怪问题

关于QTimer::singleShot的一个奇怪问题,qt,Qt,我编写了一个调用QTimer::singleShot的函数,以确保它不应该超时。但我得到了一个奇怪的结果 int Test(int x) { QEventLoop loop; QTimer timer; QObject::connect(&timer, &QTimer::timeout, [&](){ loop.exit(x); }); timer.start(7000); QTimer::singleS

我编写了一个调用QTimer::singleShot的函数,以确保它不应该超时。但我得到了一个奇怪的结果

int Test(int x)
{
    QEventLoop loop;

    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, [&](){
        loop.exit(x);
    });
    timer.start(7000);

    QTimer::singleShot(10000, std::bind(&QEventLoop::exit, &loop, 3));

    return loop.exec();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);


    qDebug() << Test(1) << endl;
    qDebug() << Test(2) << endl;

    return a.exec();
}
int测试(int x)
{
QEventLoop循环;
定时器;
QoObject::connect(&timer、&QTimer::timeout、[&](){
循环出口(x);
});
定时器启动(7000);
QTimer::singleShot(10000,std::bind(&QEventLoop::exit,&loop,3));
返回loop.exec();
}
int main(int argc,char*argv[])
{
qcorea应用程序(argc、argv);

qDebug())p>看起来像未定义的行为。至于为什么您可能会看到所描述的症状,考虑您的代码< >测试< /COD>…< /P>的实现。
int Test(int x)
{
    QEventLoop loop;

    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, [&](){
        loop.exit(x);
    });
    timer.start(7000);

    QTimer::singleShot(10000, std::bind(&QEventLoop::exit, &loop, 3));

    return loop.exec();
}
构建本地
QEventLoop
。然后设置两个计时器回调(7秒和10秒后)这两个都将退出本地事件循环。第一个超时将退出循环,导致
Test
完成并返回。但仍有一个等待超时,它还将尝试退出现在无效的
QEventLoop
。当您再次调用
Test
作为
Test(2)时
新的
QEventLoop
极有可能构建在与先前调用
Test
相同的地址。最终结果是仍然挂起的超时使用的
QEventLoop
地址变为“有效”。因此,您看到的两个值实际上来自两个超时事件从调用
测试(1)
开始

正如我一开始所说的——未定义的行为