a text on optimizing C++
Aurelien Gateau
kde-optimize@mail.kde.org
Thu, 23 Jan 2003 22:58:20 +0100
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;
}
--------------------------------------------)
Why is it bad to allocate a member in the constructor body?
Aurélien