mercredi 4 mars 2015

Strange behaviour in objective C++ when using C++11 lambdas and capturing 'self'

I have boiled down an issue which took me hours to track, but essentially comes down to this:



doSomethingLater( [self](){ NSLog(@"%x" , self); } ); // test 1
doSomethingLater( [&self](){ NSLog(@"%x" , self); } ); // test 2


Both closures are passed to a function with the following signature:



void doSomethingLater(std::function<void()> notify)


These are pseudo-code taken from a larger project where doSomethingLater is run by a boost::asio::io_service run() loop launched later on by the same thread we are currently in.


The output of test1 is nil, whereas test2 has the proper object reference.


This fully baffles me and leads me to question my most basic understanding of the language. What's going on?


What really perplexes me is why and how self could be nil (and not simply pointing to garbage as I would expect from bad reference count management going on).


One last thing to add to my confusion



[self](){ NSLog(@"%x" , self); }();


has the expected output (valid pointer to current self).


Aucun commentaire:

Enregistrer un commentaire