Re: RAII object in constructor
On 10.10.13 16.49, James Kanze wrote:
// some mutex class
class Mutex
How is this fundamentally different from `std::mutex` and
`std::lock_guard`?
In the way that is supported by my platform. ;-)
C++11 is not an option here. However, writing a mutex class does not
take more than 10 minutes. But some other features of C++11 would be nice.
Worker() : WorkerBase(AccessParams())
{ AccessParams params; // !!! Mutex acquired twice!
// do something with params...
}
};
The simplest solution (that I know) is to make the constructor
to Worker take an `AccessParams` argument:
Worker::Worker( AccessParams const& params = AccessParams() )
: WorkerBase( params )
{
}
I have gone this way now, but the hack with the default argument is new
to me. OK, it requires the AccessParams interface to be const. As long
as I do not need the RAII object itself
Worker::Worker( Params& params = AccessParams() )
: WorkerBase( params )
{}
should do as well - assuming that AccessParams has an operator Params&().
Note that if you ever use `Worker` as a temporary, the lock will
be held until the end of the full expression. This can be a bit
of a bother, if e.g. client code does something like:
func( Worker() );
The lock will be held during the entire call to func, which
could be a problem.
True, thanks for the tip. I think I keep the way with the factory
function which is safe. It has the disadvantage that Worker can no
longer be allocated as local var on the stack, but this is not intended
in my case anyway.
Marcel