TPtrC and destructor
| Wed, 2006-11-29 18:07 | |
|
Hi,
when I use a TPtrC, the buffer containing tha data,allocated in the heap mem, has to be deallocated when I don't need the descriptor yet ? TPtrC is a T-class so it doesn't need a destructor but so will the data in the heap never destroyed in the life time of the application? Thanks... |
|






Forum posts: 194
Forum posts: 49
the situation is that I have a CRichText,in a function, that has to destroyed and the textual data in it have to be returned as TPtrC.
This is the code :
TPtrC function()
{
... // richtext is a CRichText, just pushed in the cleanupstack
...
...
HBufC* copy=richText->Read(0).Alloc();
CleanupStack::PopAndDestroy( richText );
return TPtrC(copy->Ptr(),copy->Length());
}
It works but IS THERE A BETTER WAY to do it ??
Forum posts: 586
Another is to return the HBufC, renaming the method to functionL, and documenting that the caller is responsible for deleting the returned pointer.
Forum posts: 194
Your code will work (although just have return *copy) but of course copy has to be deleted at some point.
So either you
- don't destroy the CRichText until the calling code has used the TPtrC
- make the function return a HBufC* instead of a TPtrC and thus transfer ownership of the HBufC to the calling code so it is its responsiblity to delete it.
You say the data has to be returned as a TPtrC, almost certainly it doesn't, you may just think that it does.
>>One option is to push the created HBufC into the cleanupstack and rename your method to functionLC, telling the caller that there is something to be cleaned up after calling this method.
Unless I've misunderstoof your posting you can't have one function push something to the cleanupstack and then expect the caller to call PopAndDestroyjust because the function it calls has a C in its name. What if FunctionLC() pushed 2 things, or 3 things or 100 things? How does the calling function know what to do?
Forum posts: 586
But isn't the XxxLC naming convention just for this? Function Leaves and places something on the Cleanup stack for the caller to take away -- LC.
And implicitly (at least I haven't seen any explicit discussion on this) this (LC) always means that there is one and only one thing on the cleanupstack you are supposed to pop (and usually destroy).
Forum posts: 194
You listed transferring ownership of the HBufC as your 2nd option, implying it wasn't being transferred in the first option. Maybe that's not what you meant so I wanted to clarify in case any readers thought you were saying ownership wasn't transferred in the fist option, only in the 2nd.
Forum posts: 1134
and then call ->Des() on it whenever you "need" it as a TPtr, or do the TPtrC(buf->Ptr(),buf->Length()) thing whenever you need it as a TPtrC, but DO NOT do that in the function allocation the HBufC like you do now.
As other says, it might work, but it is not the right way to do it, and will create the problems you outline in your first post.