473,602 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ctor/dtor calls and ctor init seq

Good morning.

Look here:
http://groups.google.com/group/fido7...41aba5238c0f79
and here:
http://groups.google.com/group/fido7...014f4ba9df614a

Can anybody answer?

Who can't read in russian:

....
struct T
{
int *a;
T1 b;
T2 c;

void print()const throw();

T()throw(except ion&):a(0),b(0) { a=new int[10]; b...=a;}
~T()throw(){ delete[] a; a=0; }
};
....
try{ T obj; obj.b.input(); obj.print(); }catch(...){}
....

Q1: ctor throw exception during init, for ex
T()throw(except ion&):
a(0),
b(0), //throw here
/*c()*/
T::ctor user code (in {}) don't start exec. Will T::dtor be called or
no?

Q2: ctor throw exception after init, for ex
T()throw(except ion&):a(0), b(0), /*c()*/
{
a=new int[10]; //throw here
b...=a;
}
T::ctor user code (in {}) is partial (not complete) executed. Will
T::dtor be called or no?

Q3: What sequence of class-members, base class and virtual base class
is used for init:
a)seq of appearence in
list of initializers
list of inheritance
class description
b) indefinite order

Answers must be based on appropriate parts of C++ std rules (publish
complete list, pls:).

Nov 25 '06 #1
8 2730
* Grizlyk:
Good morning.
[snip]
>
Q3: What sequence of class-members, base class and virtual base class
is used for init:
a)seq of appearence in
list of initializers
list of inheritance
class description
b) indefinite order

Answers must be based on appropriate parts of C++ std rules (publish
complete list, pls:).
Please do your HOMEWORK on your own.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 25 '06 #2
Good morning.
>Alf P. Steinbach:
Please do your HOMEWORK on your own.
The local Pinkerton finds out my real desires - no hide, no run from
him!

Are anybody think another about my question? What is it, even Bazarov
keep silence for subj? Some years ago he wrote certainly something
about _ÓÔÁÎÄÁÒÔ_.

Nov 26 '06 #3
On 25 Nov 2006 20:06:39 -0800 in comp.lang.c++, "Grizlyk"
<gr*****@yarosl avl.ruwrote,
>
Are anybody think another about my question? What is it, even Bazarov
keep silence for subj? Some years ago he wrote certainly something
about _ÓÔÁÎÄÁÒÔ_.
This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[17.4] How should I handle resources if my constructors may throw
exceptions?" It is always good to check the FAQ before posting. You
can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
Nov 27 '06 #4
David Harmon ÐÉÓÁÌ(Á):
This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[17.4] How should I handle resources if my constructors may throw
exceptions?" It is always good to check the FAQ before posting. You
can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
"It is always good to check the FAQ before posting." You are right "in
general", but not right for the qwestion. The answer for this is always
short and easy for anybody, who can write C++ more then copying FAQ
examples and more then filling ready class skeleton and who can explain
at least self programs.

It is absolutly unclear why "If a constructor throws an exception, the
object's destructor is not run." One can imagin too diffrent parts of
ctor of any class, they looks like
1. list of initializers
2. code in {}
And there is absolutely no sence to treat exception from them equally.

I think, the nesgroup is group of very busy men. It is better to me to
find other :)

Nov 28 '06 #5
On 27 Nov 2006 20:16:20 -0800 in comp.lang.c++, "Grizlyk"
<gr*****@yarosl avl.ruwrote,
>It is absolutly unclear why "If a constructor throws an exception, the
object's destructor is not run."
If the constructor throws, the object is not completely constructed.
The destructor has no way to know that. A non-trivial destructor would
have no way to know what it needs to do.

If the constructor is going to throw, it should first clean up the
_part_ of the class it has built so far.
>One can imagin too diffrent parts of
ctor of any class, they looks like
1. list of initializers
Base classes and members with constructors should have their own
constructors. If some base classes and members have been constructed
when one of them throws, the destructors of the ones already constructed
are automatically run in the reverse order of construction.
>2. code in {}
There is where the "if the constructor throws" really applies. Again,
base classes and members with destructors take care of themselves, so
what you really need to look after there is unfinished business of the
{} code itself. With good RAII design there will not be too much of
that.
Nov 28 '06 #6
On Tue, 28 Nov 2006 07:05:17 GMT in comp.lang.c++, David Harmon
<so****@netcom. comwrote,
>Base classes and members with constructors should have their own
constructors .
Should be:

Base classes and members with constructors should have their own
destructors.

Nov 29 '06 #7

Grizlyk wrote in message ...
>
It is absolutly unclear why "If a constructor throws an exception, the
object's destructor is not run."
When an exception is thrown, it immediately leaves that point and starts
searching for an handler (like a 'catch'). It won't finish what it was doing
(in this case, constructing an object). If an object is not fully
constructed, it has no destructor to call (loosely speaking. See David's
post).
One can imagin too diffrent parts of
ctor of any class, they looks like
1. list of initializers
[Function–level try blocks]

class Boom : public Abase{
Boom( int a ) try : Abase(a){}catch (...){/*something*/ throw; }
};
>2. code in {}
class Boom{
int Int;
Boom( int a ){
try{
Int = a;
}
catch(...){/*something*/ throw; }
}
};
>And there is absolutely no sence to treat exception from them equally.

I think, the nesgroup is group of very busy men. It is better to me to
find other :)

See: "Thinking In C++" Volume 2: Practical Programming
(Bruce Eckel, Chuck Allison)

Part 1: Building Stable Systems
1: Exception handling

Get "Thinking in C++", 2nd ed. Volume 1&2 by Bruce Eckel
(available for free here. You can buy it in hardcopy too.):
http://www.mindview.net/Books/TICPP/...ngInCPP2e.html

--
Bob R
POVrookie
Nov 29 '06 #8
Good morning.

The two last posts: "David Harmon 28.11.2006 10:05 " and "BobR
29.11.2006 05:17 " is really very interesting to me. I will consider
them for nearest time.

And if it is interesting to anybody, i can explain my doubts more:
David Harmon wrote:
"If the constructor throws, the object is not completely constructed."
It is true.
"The destructor has no way to know that."
But it is not true. Programmer, of course, can not control a
construction sequence, but the compiler can know, what the "imagined"
part of constructor failed. Let's consider the next class:

struct A
{
int* a; //need array of int[1024]
int b;
double c;

A()throw(excepr ion&); //must allocate memory with new[]
~A()throw(); //must free memory
};

This class has only members of base C++ types. They could not throw
exception while creating own memory or data :). They have own
predefined destructors (~int etc), which completele restore system to
state befor the members created and compiler can know about their
destructors and _can calls them if the members were created_.

Lets write simple destructor of the class A:
~A::A()throw(){ delete[] a; a=0;}
The destructor of the class A has the one serious trouble - it can not
calls "delete[]" of member "a" befor operator new will return a correct
memory pointer. The data, stored in "a", is indefinite befor new will
return.

If compiler calls the dtor of the class A befor new will return a
correct memory pointer, the program will crash and make at least
"general protection fail".

Selecting way of creation ctor of the class A, we can do like this
A::A()throw(exc eprion&):a(0){/*some code*/}
The trick ":a(0)" makes dtor callings safe nearly independent from ctor
code in {}.

It is enough to guess, that compiler _can not_ call dtor of A, if list
of initializers (ctor part one) failed, and _can_ call dtor of A if all
members have been complete created successfully.

There is another important argument to the upper described compiler
behavior: all the class A members of predefined types has own ctor/dtor
pairs, i.e. all the class A members are true classes with full
incapsulated behaviour (they no need external control).

Compiler can manage creating/destroying of the members by "calling"
their trivial ctor/dtor. And executed dtor of any member of the class A
completely restore the piece of system state, which has been changed by
creating the member.

And the ctor "code in {}" of the class A must be managed by compiler in
the same manner. In order to restore all canges, have been created or
partial (not complete) created by ctor "code in {}" execution, compiler
_must_ call its dtor pair, else programmer will have to call dtor by
hand.

I do not see any sence to call destructor code from constructor myself,
for it is can be easy done by compiler.

To do it compiler can create ctor as two "imagined" part: "member_cto r"
and "user_code_ctor ". The "member_cto r" code is hidden to programmer,
the correct ctor of any member of the class A is controlled by
programmer with the help of list of initislizers. The goal of the
"member_cto r" - make calls dtor of its class safe. The goal of
"user_code_ctor " is control of its class memory. And dtor parted the
same.

Using the pattern we will have something like this:

{
A obj;
//A::compiled_cto r
// A::member_ctor( ); if(exception)go to member_ex
// A::user_code_ct or(); if(exception)go to user_ex

....

//A::compiled_dto r
//user_ex:
// ~A::user_code_d tor();
//member_ex:
// ~A::member_dtor ();
}
It is evidently, compiler must _not_ call "user_code_dtor ()" if
"user_code_ctor ()" is even not started and must call "user_code_ctor ()"
if any part of "user_code_dtor ()" executed in order to restore system
state.

In my first example any member of the class A has trivial ctor/dtor and
can not throw any exception. Let's consider second example:

struct B
{
A a;
char* b; //need array of char[256]
double c;

B()throw(excepr ion&); //must allocate memory with new[]
~B()throw(); //must free memory
};

The class A already can throw exception, but the pattern of its
ctor/dtor creating allows to compiler to use class A as true class
(with its own hidden ctor/dtor behaviour), calling
"A::compiled_ct or"/"A::compiled_dt or" in
"B::member_ctor ()"/"B::member_dtor ()". The pattern of ctor/dtor allows
to compiler restore all changes maked by partial or complete created
the member A of any class B.

One can see: any class has either members of only predefined types with
their trivial ctor/dtor and can use the ctor/dtor pattern (similar to
the class A), or members like the class B (similar to the class B). For
both cases the ctor/dtor pattern can be used, so destructor code can be
always called by compiler.

I can understand, that my explanaition is quite week and can not be
trusted "in general case".

In order to expand the explanaition to "general case" a man must be an
expert of C++ real programming and know many practical cases, to find
exceptions from my explanation. I do not see any exceptions :)

Can you object me?

Nov 29 '06 #9

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

Similar topics

2
1764
by: Eric Liu | last post by:
Hi, Can anyone explain why the following code works? The static object creation is via the private ctor. If I try to define a X object in the mainline, of course I will get complaint about calling the private ctor. I ran the code with CW8.3, it works fine. the output is: >Private ctor >dtor
3
4461
by: mescaline | last post by:
//Consider the simple program with inheritance, plain init for A, copy ctr for B #include <iostream> using namespace std; class Base{ public: Base(){cout << "Base, default" << endl;} Base(const Base &){cout << "Base, Copy Ctor" << endl;} };
10
1352
by: richardclay09 | last post by:
The output of this: #include <iostream> #include <vector> using namespace std; struct X { int i; X(const X& x) : i(x.i) { cout << "ctor copy: " << i << endl;
1
1527
by: pmastroianni | last post by:
When a class is instantiated, will the ctor and dtor occupy memory? IF ctor and dtor do occupy memory of an instantiated class where would they be in memeory?
6
1708
by: Marc Mutz | last post by:
Hi, I'm in discussion with a lib vendor who uses placement new to forward construction to another ctor, like this: MyClass( ... ) { new (this) MyClass( ... ); } I asked them to use a private init() function instead, but they claim: > you might be correct that using placement new to forward
7
1916
by: Thomas | last post by:
I have a class foo whose ctor might throw an exception. When I create a foo object using "foo* myfoo = new foo;", and the ctor throws an exception, do I need to delete myfoo to free its memory?
6
1991
by: puzzlecracker | last post by:
When ctor throws an exception, dtor is not called for that object (correct me if I am wrong) - then how would already allocated memebers de-allocated? Thanks.
9
1630
by: utab | last post by:
Dear all, How do experienced programmers using this group use the rule of thumb,namely copy ctor, assignment operator, and dtor. example if the class does not need them dont use and define them use them but dont define them (for future revisions of the class as
5
1794
by: peifeng_w | last post by:
Hi, try the following code with flag=0/1/2. #include<iostream> using namespace std; #define flag 2//option:0,1,2 class C {
0
7993
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8054
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8268
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6730
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5867
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
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
3900
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...
1
2418
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

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.