Boost logo

Boost Users :

From: Frank Birbacher (bloodymir.crap_at_[hidden])
Date: 2008-05-04 12:37:10


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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net