Can C++ objects have block scope? For example, is this ok: (it crashes)
(Go easy, I’m still learning C++)
__block Poco::Thread* lastThread;
dispatch_async(dispatch_get_main_queue(), ^
{
for (int i = 1; i <= 5; i++)
{
Poco::Runnable* worker = new Worker(_counter, "worker" + Poco::NumberFormatter().format(i));
Poco::Thread* workerThread = new Poco::Thread();
workerThread->start(*worker);
lastThread = workerThread;
}
});
lastThread->join(); //wait so we can watch what happens.
Your code is valid, nothing wrong with declaring that pointer
__blockscope. But your code will crash becauselastThreaddoes not point to any object whenjoin()is invoked. You run that block asynchronously, so almost certainlylastThread->join()is reached beforelastThreadwill point to the worker thread.