Order that things happen when returning from a function.

J

jason.cipriani

Let's say I have something like this, a class that wraps a "Mutex",
locks it on construction and unlocks it when it's destroyed (for
example):

class AutoMutex {
public:
AutoMutex (Mutex &) ... ;
~AutoMutex () ... ;
};

Now let's say I use it in a function that returns a copy of another
complex object:

class Something { ... };

Mutex TheMutex;
Something TheThing;

Something function () {
AutoMutex m(TheMutex);
return TheThing;
}

If I am using, in that example, "TheMutex" to protect access to
"TheThing", will "TheThing" be accessed before or after "m" goes out
of scope and unlocks the mutex?

Thanks,
Jason
 
H

Helge Kruse

Let's say I have something like this, a class that wraps a "Mutex",
locks it on construction and unlocks it when it's destroyed (for
example): [...]

class Something { ... };

Mutex TheMutex;
Something TheThing;

Something function () {
AutoMutex m(TheMutex);
return TheThing;
}

If I am using, in that example, "TheMutex" to protect access to
"TheThing", will "TheThing" be accessed before or after "m" goes out
of scope and unlocks the mutex?

The AutoMutex destructor is called after TheThing is accessed. If TheThing
is an struct or class, the assignemnt to the caller's object is called
before TheMutex is unlocked. If TheThing is a scalar (hold in a register),
the value is saved before calling Mutex destuctor.

/Helge
 
J

jason.cipriani

The AutoMutex destructor is called after TheThing is accessed. If TheThing
is an struct or class, the assignemnt to the caller's object is called
before TheMutex is unlocked. If TheThing is a scalar (hold in a register),
the value is saved before calling Mutex destuctor.

Thanks. :)

Jason
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top