Re: How to allocate new class instance on the heap?



On 25 May 2005 17:14:26 -0700, chrisspencer02@xxxxxxxxx wrote:

>Just to make sure I understand you:
>
>ClassInstanceVariable := tClassName.Create { ( <constructor
>parameters>) };
>
>This will allocate ClassInstanceVariable on the heap, and will not
>automatically deallocate it when the function declaring
>ClassInstanceVariable exits? Thanks.

Nearly right.

It will put a 4 byte pointer into ClassInstanceVariable
- those 4 bytes point to a chunk of data on the heap
- the chunk of data will not be deallocated when you leave the
function/procedure
- the chunk of data will only be deallocated when you (or if it has an
owner, its owner) does ClassInstanceVariable.Free

What happens to ClassInstanceVariable (just the 4 byte pointer)
depends on where you declared it.

If you are not careful you could land up with an 'orphan' on the heap.

BTW - I would not go around using New and Dispose to create and
destroy Records
- not unless you are doing something really fancy
- just declare them as a Var on the stack and let Delphi create and
destroy them for you

You do (generally) need to zap their contents before using them, as
annoyingly Delphi does not do that for you (except when it does - but
it is better to play it safe)


.



Relevant Pages

  • Re: Creating member vars on the heap, not the stack
    ... on the heap, not the stack. ... Other than declaring all the members of the class as static, ...
    (microsoft.public.vc.language)
  • Re: Passing more than 1 param in AfxBeginThread
    ... what is the difference between declaring the the pointer *p on the heap and then deleting after finishing with it, and just declaring it on the stack? ... If you declare a variable on the stack it disappears when the function ...
    (microsoft.public.vc.mfc)
  • Re: Passing more than 1 param in AfxBeginThread
    ... what is the difference between declaring the the pointer *p on the heap and then deleting after finishing with it, and just declaring it on the stack? ... What i want to know is when should i declare a var on the heap instead of on the stack? ...
    (microsoft.public.vc.mfc)