RPointerArray

Sorting custom objects


Objects stored in RArray or RPointer array can be sorted basing on any properties you like. Everything you have to do is to define a comparison function to be passed to the Sort() routine.

Here is an example on how to sort the custom CPerson objects by the last name. Note the use of CompareC for taking into account the locale specifics, when comparing strings.

Protecting the RPointerArray content against the leave – CleanupResetAndDestroyPushL

Every object allocated on the heap should be protected by pushing its pointer to the cleanup stack via CleanupStack::PushL. Kernel resources used by the R-objects like RPointerArray are protected via CleanupClosePushL.

Sometimes you’d like or have to protect all the RPointerArray content without pushing all the individual items to the cleanup stack. There are custom solutions for this purpose, but there is also a built-in facility – CleanupResetAndDestroyPushL. It is not well known and not widely used only because it is defined in a quite an unusual place - \epoc32\include\mmf\common\mmfcontrollerpluginresolver.h

Tip: protect both the RArray and its contents

Update: "new (ELeave) RStringArray" was missing the "ELeave" (thanks to Tote)

Lately I worked with the API that required passing the RPointerArray allocated on the heap so that ownership was passed to that API. It is quite a rare case, but demonstrates nicely how tricky the CleanupStack protection can sometimes be. Note the order of pushing to the cleanup stack. If CleanupClosePushL was called first and leave happened during the CleanupStack::PushL, memory leak would occur.


// Local Functions
typedef RPointerArray RStringArray;
...
HBufC* element1 = HBufC::NewLC( 10 );
HBufC* element2 = HBufC::NewLC( 20 );
RStringArray* array = new (ELeave) RStringArray;
// Protect the allocated heap mem
CleanupStack::PushL( array );
// Protect the kernel handle/array contents
CleanupClosePushL( *array );
array->AppendL( element1 );
array->AppendL( element2 );

CleanupStack::PopAndDestroy( array ); // Close the array
CleanupStack::PopAndDestroy( array ); // And free the heap mem
...

Syndicate content