std::auto_ptr and Unwind Order?

J

Jamie Burns

Hello,

I am trying to write some threadsafe code. I am using mutexes to restrict
access to certain class members. Consider the method below:

// begin code nippet

bool rControl::getVisibility() {

{

std::auto_ptr<rMutexAccess> mutexAccess(new
rMutexAccess(this->objectMutex));

// get visibility

return visible;

}

}

// end code nippet

So, basically, I am creating the mutex using an auto_ptr to give myself a
guarantee that the mutex will unlock (it unlocks on destruction of the
rMutexAccess) no matter what happens in the code.

My question is this: in the above code, which happens first? A) Does the
member "visible" get copied to be returned, after which the mutex destructs,
or B) The mutex destructs, and then the member "visible" get copied to be
returned.

Can you see what I am getting at? In normal code it is fine, I can see
clearly what will happen, but with a "return" statement inside the protected
nest { ... } I am not sure what happens.

Thanks!

Jamie Burns.
 
I

Ivan Vecerina

Hi Jamie,
....
| // begin code nippet
|
| bool rControl::getVisibility() {
|
| {
|
| std::auto_ptr<rMutexAccess> mutexAccess(new
| rMutexAccess(this->objectMutex));
|
| // get visibility
|
| return visible;
|
| }
|
| }
|
| // end code nippet
|
| So, basically, I am creating the mutex using an auto_ptr to give myself a
| guarantee that the mutex will unlock (it unlocks on destruction of the
| rMutexAccess) no matter what happens in the code.

First of all, note that it is unnecessary to use an auto_ptr here.
You can simply rely on an automatic (stack-based) variable:
{
rMutexAccess mutexAccess(this->objectMutex);
return visible;
}

| My question is this: in the above code, which happens first? A) Does the
| member "visible" get copied to be returned, after which the mutex
destructs,
| or B) The mutex destructs, and then the member "visible" get copied to be
| returned.

The returned expression is first evaluated and copied as the
function's result value. Then the function scopes are exited,
and all the stack based objects will be destroyed.
[at least that's my reading of the standard, §6.6,
but this is what happens in practice if you try to test it]

So your code snipped is ok, although I think it has to be simplified...


hth-Ivan
 
J

Jamie Burns

Thanks Ivan!

Of course I don't need auto_ptr! Silly me!

Good to know the variable copy comes first...

Jamie.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top