When Initialization Lists shall not be used?

P

pasa_1

Can someone clarify few items from FAQ
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

'[10.6] Should my constructors use "initialization lists" or
"assignment"?'

a. This might happen when your class has two constructors that need to
initialize the 'this' object's data members in different orders. <--
Okay

b. Or it might happen when two data members are self-referential. <--
Can someone clarify this?

c. Or when a data-member needs a reference to the this object, and you
want to avoid a compiler warning about using the this keyword prior to
the { that begins the constructor's body (when your particular compiler
happens to issue that particular warning). ?? An example will be
helpful.

d. Or when you need to do an if/throw test on a variable (parameter,
global, etc.) prior to using that variable to initialize one of your
this members. ?? An example will be helpful.

Regards,
Manish
 
V

Victor Bazarov

pasa_1 said:
Can someone clarify few items from FAQ
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6

'[10.6] Should my constructors use "initialization lists" or
"assignment"?'

a. This might happen when your class has two constructors that need to
initialize the 'this' object's data members in different orders. <--
Okay

b. Or it might happen when two data members are self-referential. <--
Can someone clarify this?

Not sure what's meant here, but if 'plast' needs to point to the last
element of a dynamically allocated array, you can either reoder the
members and initialise plast in the initialiser list or use assignment
like here:

struct A {
int *plast;
int n;
int *p;
A(int nn) : n(nn), p(new int[nn]) { plast = p[n-1]; }
};
c. Or when a data-member needs a reference to the this object, and you
want to avoid a compiler warning about using the this keyword prior to
the { that begins the constructor's body (when your particular
compiler happens to issue that particular warning). ?? An example
will be helpful.

struct A {
A* self;
A() : self(this) {} // can get a warning about use of 'this'
A(int) { self = this; } // no warning
};
d. Or when you need to do an if/throw test on a variable (parameter,
global, etc.) prior to using that variable to initialize one of your
this members. ?? An example will be helpful.

'throw' is a statement, and IIRC has to be in the body. OTOH, I am
not sure it cannot be circumvented with a static member function in
which you could both check and throw (and return the value to boot)...

V
 

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,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top