Board index » cppbuilder » TStringList *Function();

TStringList *Function();

I've got a function which creates new TStringList and returns a pointer to
it.

I want to fill a listbox with the output
can I do it like this:

ListBox1->Items->AddStrings(Function());

or do I need to delete this StringList after filling listbox:

TStringList *temp = Function();
ListBox1->Items->AddStrings(temp);
delete temp;

thanks
Maciek

 

Re:TStringList *Function();


Why not do it the other way round - change your function to take a TStrings* as
a parameter:

Function( TStrings * StrList)
{
StrList->Clear() ;
StrList->Add( ...) ;
StrList->Add( ...) ;
...

Quote
}

Then call it with:

Function( ListBox1->Items) ;

  Max.

Quote
"Maciek" <mac...@lm.pl> wrote in message news:8r01kr$7lh7@bornews.borland.com...
> I've got a function which creates new TStringList and returns a pointer to
> it.

> I want to fill a listbox with the output
> can I do it like this:

> ListBox1->Items->AddStrings(Function());

> or do I need to delete this StringList after filling listbox:

> TStringList *temp = Function();
> ListBox1->Items->AddStrings(temp);
> delete temp;

Re:TStringList *Function();


Yes, you will have to delete it. Every "new" needs a corresponding "delete".
Actually it's bad practice to return a pointer to an object created with new
in a function , in this case a "new TStringList". Each function should be
responsible for its own memory allocation & deletion. If you forget to delete
it via the returned pointer you'll have a memory leak. (See Scott Meyers C++
books on the subject.)
Instead, consider sending the function a TStringList object via a reference
parameter:

bool Function(TStringList& sl)
{
    ...fill sl with strings...
    ...return true if the function worked ok.

Quote
}

TStringList *temp = new TStringList;
if(Function(*temp))
    ListBox1->Items->AddStrings(temp);
delete temp;

Dave K.
~~~~

Quote
Maciek wrote:
> I've got a function which creates new TStringList and returns a pointer to
> it.

> I want to fill a listbox with the output
> can I do it like this:

> ListBox1->Items->AddStrings(Function());

> or do I need to delete this StringList after filling listbox:

> TStringList *temp = Function();
> ListBox1->Items->AddStrings(temp);
> delete temp;

> thanks
> Maciek

Other Threads