a text on optimizing C++

Benjamin Meyer kde-optimize@mail.kde.org
Thu, 23 Jan 2003 18:13:10 -0500


On Thursday 23 January 2003 4:58 pm, 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): Giv=
en
> 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 initializati=
on
> list.
> [snip]
> If you don't always need to have a pointer member in existence during t=
he
> 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 =3D new PointerMember( inParam );  // DON'T DO THIS
>    return;
> }
> --------------------------------------------)
>
> Why is it bad to allocate a member in the constructor body?
>

if that member is used all throughout the class then it should be initial=
ized,=20
but if the member is used sparingly then you want to initialize it only w=
hen=20
it is used.  This way when the class construction is called it wont waste=
 its=20
time setting up variables that are never used for simple functions.

-Benjamin Meyer