a text on optimizing C++

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


On Friday 24 of January 2003 14:03, Lubos Lunak wrote:
> On Thursday 23 of January 2003 22:58, Aurelien Gateau wrote:
> > Alexander Neundorf wrote:
> > // User.cpp
> > #include "User.h"
> > User::User( const RefParam &inParam )
> >    : mPointerMember( new PointerMember( inParam ) )
> > {}

 BTW, one more thing. Note that this part starts with 'What to you do if the 
member variable's header file is big and complex'. I really don't like code 
like that above or this:

 KConfig*cfg = new KConfig( "somerc" );
 cfg->writeEntry( "Entry", "Value" );
 delete cfg;

 This is sooo lame. If the code will get a bit more complicated, it's a nice 
attempt to introduce a leak. The following code

 { 
 KConfig cfg( "somerc" );
 cfg.writeEntry( "Entry", "Value" );
 }

 is exactly the same (and the {}'s are not needed if the calling of the 
destructor may wait until the end of the function/block it's in). It saves 
one dynamic allocation and deallocation, and there will be no leak.

 Unless there's a reason to save the #include in the .h file, the User class 
example can become simply

User::User( const RefParam &inParam )
   : mPointer( inParam )
{}

 No need to call delete in the destructor. In both cases, the attribute is 
created in the constructor and destroyed in the destructor.

-- 
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/