Re: Order of destructor execution.
<eshneto@gmail.com> wrote in message
news:1185206636.669199.117390@w3g2000hsg.googlegroups.com...
Sorry if this may seem to be very obvious, but it is important and I
decided to ask.
I have the following classes:
class MutexWrapper
{
public:
MutexWrapper( void );
void lock( void ); //Maybe const, whatever.
void unlock( void ); //As well.
~MutexWrapper( void );
}
class MutexLocker
{
public:
MutexLocker( MutexWrapper& mut ){ mut.lock(); } //Perhaps it
could be const MutexWrapper& mut (?)
~MutexLocker( void ){ mut.unlock(); }
}
So that I want to sync acces to the variable
volatile unsigned cont
in the following piece of code (supposing there is a global
MutexWrapper mut ):
unsigned getCont( void )
{
MutexLocker( mut );
You are not storing the instance of MutexLocker anywhere. It is created,
then prompty destroyed.
return( cont );
At this point your MutexLocker is already destroyed.
}
Will the destructor ~MutexLocker() be executed before the copy
constructor of unsigned? It seems logical if this return statement
could be interpreted as a placement new in the adress given by the
return variable, something like the equivalence of:
c = getCont();
and
{
MutexLocker( mut );
new( &c ) unsigned( cont );
}
If so, my code seems to be correct. Is it true?
You need to store your MutexLocker somewhere.
unsigned getCont( void )
{
MutexLocker LockIt( mut );
return( cont );
}
By giving the MutexLocker a variable name, its lifetime is the lifetime of
the function/method.
The quesiton still becomes, which is done first, the destruction of LockIt
or the retriving of the cont value? I'm not really sure, someone might
know. But being unsure I would do this.
unsigned getCont( void )
{
MutexLocker LockIt( mut );
unsigned ReturnVal = cont;
return( ReturnVal );
}
I know for a fact that ReturnVal is going to be assigned while the instance
of the MutexLocker is still there. It may not be necessary, but I know it
would work.