a text on optimizing C++

Lubos Lunak kde-optimize@mail.kde.org
Fri, 24 Jan 2003 14:03:10 +0100


On Thursday 23 of January 2003 22:58, Aurelien Gateau wrote:
> Alexander Neundorf wrote:
> > especially http://www.goingware.com/tips/parameters/
>
> This is a great resource. However, I fail to understand the following
> advice (from http://goingware.com/tips/parameters/membervars.html): Given
> this code example:
>
> (--------------------------------------------
> // User.cpp
> #include "User.h"
> User::User( const RefParam &inParam )
>
>    : mPointerMember( new PointerMember( inParam ) )
>
> {}
> --------------------------------------------)
>
> The authors writes:
>
> (--------------------------------------------
> Note that it is terribly important that you initialize pointer members
> (actually any member) of your objects in the constructor's initialization
> list.
> [snip]
> If you don't always need to have a pointer member in existence during the
> lifetime of your object, you may choose to initialize it to nil [snip]. If
> the pointer is going to need to be allocated before the constructor is
> done, always do it in the initialization list, not in the body of the
> constructor, like this:
>
> User::User( const RefParam &inParam )
> {
>    mPointerMember = new PointerMember( inParam );  // DON'T DO THIS
>    return;

 This 'return' here looks really funny.

> }
> --------------------------------------------)
>
> Why is it bad to allocate a member in the constructor body?

 I think the reason is that it's more sure the instance is correctly 
initialized when using the initializer list (at least I think that's the 
reasoning in the text). There's nothing really bad about doing 
initializations in the body, but is there really a reason to do this

Class::Class( int arg1, const QString& arg2 )
{
    attr1 = arg1;
    attr2 = arg2;
    attr3 = 0;
    attr4 = new AnotherClass;
}

and not this?

Class::Class( int arg1, const QString& arg2 )
 :  attr1( arg1 ),
    attr2( arg2 ),
    attr3( 0 ),
    attr4( new AnotherClass )
{
}

 It looks almost the same, but the latter may also sometimes produce shorter 
code. Upon entering the constructor body, all constructors of attributes have 
already been executed. So in this example, in the latter case attr2 is 
directly initialized using a copy constructor, while in the sooner case it's 
initialized using the default constructor, and then operator= is used.

 When using the initialization list, you sometimes have to use static 
functions for more complex initializations, or sometimes even those can't 
help and the initialization has to be done in the body, but this is the C++ 
way of doing it.

-- 
Lubos Lunak
KDE developer
---------------------------------------------------------------------
SuSE CR, s.r.o.  e-mail: l.lunak@suse.cz , l.lunak@kde.org
Drahobejlova 27  tel: +420 2 9654 2373
190 00 Praha 9   fax: +420 2 9654 2374
Czech Republic   http://www.suse.cz/