473,671 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Order of destructor execution.

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 );
return( cont );
}

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?

Thanks,
Elias.

Jul 23 '07 #1
7 2692
es*****@gmail.c om wrote:
[..]
unsigned getCont( void )
{
MutexLocker( mut );

Not sure what 'mut' here is, but if it's a global object of some
kind, then the statement above creates (and immediately discards)
a temporary value of type 'MutexLocker'. The destructor for that
temporary is called before the following 'return' statement is
exectuted.
return( cont );
}

Will the destructor ~MutexLocker() be executed before the copy
constructor of unsigned?
There is no "copy constructor of unsigned". Does all that clarify
the situation?
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?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 23 '07 #2
<es*****@gmail. comwrote in message
news:11******** **************@ w3g2000hsg.goog legroups.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.
Jul 24 '07 #3
On Jul 23, 7:24 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
eshn...@gmail.c om wrote:
[..]
unsigned getCont( void )
{
MutexLocker( mut );
Not sure what 'mut' here is,
It doesn't matter.
but if it's a global object of some
kind, then the statement above creates (and immediately discards)
a temporary value of type 'MutexLocker'.
No. That statement declares a variable mut, of type
MutexLocker. If MutexLocker doesn't have a default constructor,
it is illegal, and the compiler should complain. If MutexLocker
does have a default constructor, then it is called.
The destructor for that
temporary is called before the following 'return' statement is
exectuted.
The destructor of mut is called on leaving the function.
return( cont );
}
Will the destructor ~MutexLocker() be executed before the copy
constructor of unsigned?
There is no "copy constructor of unsigned". Does all that clarify
the situation?
Conceptually, cont can be copied, as if it had a copy
constructor. The destructor of the variable mut will be called
after this copy.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 24 '07 #4
On Jul 23, 6:03 pm, eshn...@gmail.c om wrote:
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 ):
Just curious as to what you thing the volatile is going to do
here. (Under Posix, at least, and supposing that your
MutexWrapper actually wraps a pthread_mutex_t , all it does is
slow up your code, without providing any additional guarantees.)
unsigned getCont( void )
{
MutexLocker( mut );
If the above compiles, it's time to change compilers.
MutexLocker doesn't have a default constructor, so you can't
declare an instance of it without providing an argument.
return( cont );
}
Will the destructor ~MutexLocker() be executed before the copy
constructor of unsigned?
Since the code won't compile, it's hard to say anything about
its runtime behavior. Local variables however, will only be
destructed after the return value has been copied to where ever
it is to be copied to.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jul 24 '07 #5
>
It doesn't matter.
No, it does matter.
In the code MutexLocker could be a function or it could be a class
with similar use as scoped_lock (to lock a mutex on constructor and
unlock it on destructor). If it's a class, then there's a problem with
the code because this statement doesn't really lock scope of the
function, it will only wait until lock is released by other threads
and then will return immediately unlocking the mutex object because
the mutexlock object is nowhere and it will be destructed immediately.
You may check all that by stepping through the code with debugger.
>
No. That statement declares a variable mut, of type
MutexLocker. If MutexLocker doesn't have a default constructor,
it is illegal, and the compiler should complain. If MutexLocker
does have a default constructor, then it is called.
No, it's all wrong. Usually, mutexlocker by semantics has to be
noncopyable (no assignment or copy constructor) and non default
constructible too.
>
The destructor of mut is called on leaving the function.
No, it's wrong, destructor will be called right before the next line.

....
All these questions were clearly answered in previous posts, did you
try to read them at least??
I think you made a mistake thinking that MutexLocker ( mut ); is the
same as MutexLocker mut;
Just curious as to what you thing the volatile is going to do
here.
As far as I'm concerned volatile only removes optimizations in the
code that involves this variable (basically, if value of this variable
is stored in a cpu register and then if some operation should be
performed on the variable the stored value of the variable will not be
used - it will again be reloaded from memory because it's assumed that
the memory cell possibly was modified by other thread. BUT it doesn't
not guarantee at all any atomicity, e.g. some other thread may have
modified the variable and still didn't put the modified value back to
memory cell... http://en.wikipedia.org/wiki/Volatile_variable

Jul 24 '07 #6
__PPS__ wrote:
[..]
I think you made a mistake thinking that MutexLocker ( mut ); is the
same as MutexLocker mut;
It is, if 'MutexLocker' is a type. I actually made a mistake of
thinking it would be a creation of a temporary object (that's all
*if* 'MutexLocker' is a type), but it isn't. Here is the test you
can run

class MutexLocker {
public:
MutexLocker() {} // default c-tor
MutexLocker(int ) {} // parameterized c-tor
operator int() const { return 42; }
};

int mut = 0;

int main() {
MutexLocker(mut );
return mut;
}

What do you think this program's "main" will return to the system?
Please explain.

Another example, similar, of ill-formed code:

class MutexLocker {
MutexLocker() {} // default c-tor -- private!!!
public:
MutexLocker(int ) {} // parameterized c-tor
};

int mut = 0;

int main() {
MutexLocker(mut ); // should not compile
}

Now, if 'MutexLocker' is NOT a type but instead, say, a macro that
expands into something like

MutexLocker_t someUniqueVaria bleName123456(m ut);

then further clarification may be required.
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 24 '07 #7
As I see, this discussion is done with. I rewrote my code and initial
post as I meant and clarified the question based on the answers I got.
Two questions were answered: the one I actually wanted to ask and
another interesting one due to a typing error.

The typing error was to forget the name of the automatic variable to
be created, leaving the compiler to think that the argument I intended
to use for creation was the name of the object. I wrote

MutexLocker( mut ); //Fails on attempt to create an object named mut
//with default constructor.
//It does not create a temporary.

when I meant:

MutexLocker lock( mut );

where, as said, mut is a global MutexWrapper. The hole post is
rewritten here with comments on the answers, all of them tested.

First the post as I meant:
>I have the following classes:

class MutexWrapper
{
public:
MutexWrapper( void ){ pthread_mutex_i nit( &_mut, NULL ); }
void lock( void ){ pthread_mutex_l ock( &_mut ); }
void unlock( void ){ pthread_mutex_u nlock( &_mut ); }
~MutexWrapper( void ){ pthread_mutex_d estroy( &_mut );}

private:
pthread_mutex_t _mut;

}

class MutexLocker
{
public:
MutexLocker( MutexWrapper& mut ) : _mut( mut ) { mut.lock(); }
~MutexLocker( void ){ _mut.unlock(); }
private:
MutexWrapper& _mut;

}

So that I want to sync acces to the variable

volatile unsigned cont;
Which, by the way, is volatile because I do not want optimization to
mess loops such as while( cont < n );
I hope this answers one of Kanze's questions.
>
in the following piece of code, supposing there is a global
MutexWrapper mut:
Here was the error in my first post. Whatever that creepy piece of
code meant, it was not what I had in mind. The actual code is:
>
unsigned getCont( void )
{
MutexLocker lockIt( mut );
return( cont );
}

Will the destructor ~MutexLocker() be executed before the return statement?
Langston got the typing error, but still did not answer to the main
question:

"
>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 );

}
"

Which was later answered by Kanze:

"
>Conceptually , cont can be copied, as if it had a copy
constructor. The destructor of the variable mut will be called
after this copy.
"

In the same post he also clarifies the "default constructor versus
temporary creation" issue.

How did I test it?

By stepping through the correct code with gdb it becomes clear that
the return( cont ); statement is executed before the destructor for
lockIt.

Trying to compile the code given in my first post with g++ gives:

error: no matching function for call to 'MutexLocker::M utexLocker()'

because it is not defined at all, showing which constructor is
actually called.

Thanks,
Elias.

Aug 1 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3654
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc. And i have things to offer, and to request. And a lot of ideas, but who needs them.... here's an example (from type_struct.py):
52
26999
by: Newsnet Customer | last post by:
Hi, Statement 1: "A dynamically created local object will call it's destructor method when it goes out of scope when a procedure returms" Agree. Statement 2: "A dynamically created object will call it's destructor when it is made a target of a delete".
5
2668
by: Mark | last post by:
When declaring a class that uses multiple inheritance, does the order used when listing the inheritance matter? I'm finding with my compiler (gcc 3.2.2) that my program seg faults when destructing if the order is "wrong". In my program I use an STL vector to store objects of type Server *. Server is an abstract base class. When exiting my program I iterate through the vector and call delete on all my Server objects. One of the...
16
1855
by: Timothy Madden | last post by:
Hy I have destructors that do some functional work in the program flow. The problem is destructors should only be used for clean-up, because exceptions might rise at any time, and destructors will be called for clean-up only. So how can I tell, from within the destructor, if the call has been made as part of normal flow of control and the destructor can play its functional role, or if the call has been made as a result of an...
11
4351
by: santosh | last post by:
Hello, I was going through the Marshal Cline's C++ FAQ-Lite. I have a doubt regarding section 33.10. Here he is declaring a pure virtual destructor in the base class. And again defining it inline. Like this.
4
2279
by: blackswift | last post by:
Hello,all I hava a problem that when did cout call its destructor? I used GCC compiler under linux , It compiles OK. and gives me : cons des as I haved expected.
11
1980
by: AB | last post by:
Hi All, I've got an array of objects, during the execution of the program I'd like to assign a particular object to a certain element in the object array. The sample code's like this... class ClassA { public: ClassA()
13
2678
by: Thomas Mlynarczyk | last post by:
Hi, I have this code: class Test { public $status = 'dead'; function __construct() { $this->status = 'alive'; } function __destruct() { echo '<br>__destruct()'; } }
7
3407
by: BeautifulMind | last post by:
In case of inheritence the order of execution of constructors is in the order of derivation and order of destructor execution is in reverse order of derivation. Is this case also true in case class is derived as virtual? How does the order of construction/destruction is impacted if the base class is derived as virtual or non virtual? just see the example below.
0
8483
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8401
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8824
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
5703
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4416
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2818
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2060
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.