I have the following code that uses a C ++ object of the Datum class in the Objective-C work function:
void work(const Datum &datum) { dispatch_async(dispatch_get_main_queue(), ^{
This code is called with the instance, which is actually boost::shared_ptr<Datum> , i.e.
boost::shared_ptr<Datum> the_datum(new Datum()); work(*the_datum);
In this situation, it is possible that the_datum instance will be freed before the block is started inside work (the dispatch_async call performs an asynchronous operation on the Datum , which is executed later, the call and, therefore, the work function returns immediately). This obviously leads to disaster.
One solution may be to not pass a link to work , but instead boost::shared_ptr<Datum> . But there may be situations where links are preferred; see, for example, this thread . Is there a way to keep the work interface (i.e. Pass Datum as a reference), but still prevent the release of the shared pointer until the block completes?
source share