
Hi! Jose Martinez schrieb:
Frank, David, Nat, Thank you very much for the info. I picked up some good tips from ur responses.
:)
I made 'int d_count' a reference counter to find out how many copies are created and it went as high as 11; why so many?
Function objects are considered lightweight and are passed by value on every function call. The compiler might eliminate some copies, but because you are doing the debug output in the copy ctor it might not. And most important: 11 copies are not a problem until your profiler shows it is.
I tried implementing the 'int count' member as a pointer, following Frank's advice, but I keep getting segmentation faults. [snip] Here is the code: print (boost::asio::io_service& io, boost::asio::deadline_timer* timer) : t(timer) { d_count++; *count = 0; std::cout<<"I'm in constructor: "<<*count<<"\n"; t->async_wait(*this); }//end print
The segmentation fault occurs because the "count" pointer is not initialised. Instead you dereference the uninitialised pointer during "*count = 0;" which invokes "undefined behaviour" (a C++ std term): your program may do anything after that. Try: print( /*boost::asio::io_service& io,*/ //is not needed, is it? boost::asio::deadline_timer& timer, int& externalCount ) : t(&timer) , count(&externalCount) { //... } and in your main:
int main(){ boost::asio::io_service io; boost::asio::deadline_timer t(io, boost::posix_time::seconds(1)); int myCount = 0; //user might do initialization herself print p(&t, myCount);
io.run(); return 0; }
Regards, Frank