Namespaces
Variants
Actions
Revision as of 03:43, 15 June 2012 by hamishwillee (Talk | contribs)

Avoiding memory leaks during transfer of ownership

Jump to: navigation, search
Article Metadata

Compatibility
Platform(s): S60

Article
Created: User:Technical writer 1 (26 Nov 2007)
Last edited: hamishwillee (15 Jun 2012)

Description

The following code demonstrates a common pattern for creating memory leaks:

 User::LeaveIfError(bar.TakesOwnershipIfSuccessful(CFoo::NewL()));

If the construction of CFoo succeeds, but then the function call that is supposed to take ownership of it fails, then the newly-created CFoo instance is orphaned.

Solution

The only way to do this safely is to use the cleanup stack:

 CFoo* foo = CFoo::NewL();
 CleanupStack::PushL(foo);
 User::LeaveIfError(bar.TakesOwnershipIfSuccessful(foo));
 CleanupStack::Pop(foo);


The most common situations where these kind of leaks occur are array operations such as Append() or Insert().

98 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved