I am learning boost :: asio and C ++ 11 at the same time. One of my test programs, which is actually an adaptation of one of the examples given in the boost :: asio manual , is this:
#include <iostream> #include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> class printer { // Static data members private: const static boost::posix_time::seconds one_second; // Instance data members private: boost::asio::deadline_timer timer; int count; // Public members public: printer(boost::asio::io_service& io) : timer(io, one_second), count(0) { std::function<void(const boost::system::error_code&)> callback; callback = [&](const boost::system::error_code&) { // critical line if (count < 5) { std::cout << "Current count is " << count++ << std::endl; timer.expires_at(timer.expires_at() + one_second); timer.async_wait(callback); } }; timer.async_wait(callback); } ~printer() { std::cout << "Final count is " << count << std::endl; } }; const boost::posix_time::seconds printer::one_second(1); int main() { boost::asio::io_service io; printer p(io); io.run(); return 0; }
When I run this program, I get a segmentation error. I understand why I get a segmentation error. After the constructor completes, the callback constructor variable goes out of scope, and the lambda callback variable, which is a reference to the callback constructor variable, becomes a link.
Therefore, I modify the curve with:
callback = [callback, &](const boost::system::error_code&) { // critical line
Then compile it, run it and get a function error message. Again, I understand why I get a function error error. Within the lambda region, the callback constructor variable has not yet been assigned any value, so for all practical purposes this is a dangling function pointer. Therefore, the callback lambda variable, which is a copy of the callback constructor variable, is also a pointer to dangling functions.
After thinking about this problem for a while, I realized that I really need the callback to be able to refer to itself using a function pointer, not a reference to a function pointer. The sample achieved this by using the named function as a callback rather than anonymous. However, passing these functions as callbacks is not very elegant. Is there a way to get an anonymous function, is there a pointer to the function as a local variable?