调用方堆栈无效后,回调func引用的调用方本地变量如何?

问题描述

我认为以下代码由于本地变量“不可用”而可能存在潜在问题,行为是否应定义?

class foo {
public:
    foo(){
        std::cout << "foo constructed" << std::endl;
    }
    ~foo(){
        std::cout << "foo destructed" << std::endl;
    }
    int val;
};
void do(std::function<void()> func) {
    // let other thread to invoke func
    dispatch_async(conqueue,^{
        sleep(5); // wait 5s for testLocalRef return,so all local variable should be invalid due to stack popup?
        func();
    });
}
void testLocalRef() {
    auto res = true; // local variable
    foo fo; // local variable
    std::function<void()> func = [&res,&fo] () {
        res = false; // invalid? the behavior is undefined?
        fo.val = 10; // invalid? the behavior is undefined?
        std::cout << "callback"<<std::endl;
    };
    do(func); // return immediately
}
int main(int argc,const char * argv[]) {
    conqueue = dispatch_queue_create("MyConcurrentDiapatchQueue",disPATCH_QUEUE_CONCURRENT);
    testLocalRef();
    // other function calls in order to use the stack
    // ...
    CFRunLoopRun(); // no return
}

能请你帮我吗?预先感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...