Boost logo

Boost Users :

Subject: Re: [Boost-users] [thread] About the virtual in virtual operator()
From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2009-11-02 05:19:44


Richard Vock <vock_at_[hidden]> writes:

> I don't really know wether this is a Boost.Thread related
> question or a general c++ related, but since I couldn't
> decide I will disturb you first ;)
>
> Maybe you have the patience to look at this minimalistic
> framework (I stripped almost all functionality):
>
> http://pastebin.com/m7dcc833f
>
> This compiles well and running it gives me the expected:
>
> # starting
> # This is A
> # This is B
> # shutting down
>
> The problem is, that I want to run the kernels as threads.
> Have (again) a look at the highlighted lines (27-29):
>
> If I replace 27 by 28+29 I (expectedly) get a compile error
> since Kernel is abstract. However if I make it non-abstract
> by implementing the operator() in it, it is this function
> (namely Kernel::operator()) which get's called instead of
> TestKernel::operator().

Yes. This is because boost::thread copies the objects into the new
thread. You can't copy an object through a reference to abstract base
since you cannot create an instance of the base class. If you make the
base non-abstract then it slices, and calls the base operator().

You can use boost::ref to fix this:

boost::thread t(boost::ref(*m_kernel[i]));

Of course you have to ensure that the m_kernel objects outlive the
threads if you do this.

Anthony

-- 
Author of C++ Concurrency in Action | http://www.manning.com/williams
just::thread C++0x thread library   | http://www.stdthread.co.uk
Just Software Solutions Ltd         | http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

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