Jump to content
dummzeuch

What's the correct way to free an object in C++Builder?

Recommended Posts

I got a bug report that the C++ code generated by the Components to Code expert to free a component is wrong.

 

Currently it generates this:

    TEdit *Edit1;

    Edit1 = new TEdit((TComponent *)NULL);

    Edit1->Name = "Edit1";
    Edit1->Parent = ParentPanel;
    Edit1->Left = 56;
    Edit1->Top = 8;
    Edit1->Width = 121;
    Edit1->Text = "Edit1";

    delete[] Edit1;

According to David G. Hoyle it should be done like this:

delete Edit1;

but according to the bug report it should be:

 Edit1->Free();

I tend to believe Dave, but since I don't do any C++ Builder programming, I don't know which syntax is correct.

Edited by dummzeuch

Share this post


Link to post

I believe X->Free() is coming from the Delphi compatibility and is only used when importing Delphi object. Meaning it works only with TObject descendant. On the other hand delete X is a standard c++ operator that works with all objects whether they descend from TObject or not.

On this page, there is an explicit note that says

Quote

Note: In C++ code, do not use Free to destroy an object. Use the delete keyword.

 

  • Thanks 1

Share this post


Link to post

Yes, do not use TObject::Free() in C++, use the native delete operator instead.  The delete[] operator is for freeing arrays allocated with the new[] operator, so the generated code is definitely wrong in that regard.  A general rule of thumb is:

 

allocator ->deallocator

new -> delete (single item)

new[] -> delete[] (array of items)

(m|c|re)alloc() -> free() (C runtime)

 

I also question the expert's decision to set the component's Owner to NULL, but without knowing what the expert actually does and what its input is, I could not say for sure if that is correct or not.

Edited by Remy Lebeau
  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×