Jump to content
pyscripter

Initialization of returned managed types

Recommended Posts

I guess everyone knows this already, but I did find this Stackoverflow answer surprising.  Can you guess what is the message shown?

function DoSomething(SomeBoolean: Boolean) : string;
begin
    if SomeBoolean then
        Result := 'abc'
end;

procedure TForm1.Button1Click(Sender: TObject);
var
    xx: string;
begin
    xx := DoSomething(True);
    xx := DoSomething(False);
        ShowMessage(xx);
end;

Shouldn't the above deserve a compiler warning?

Edited by pyscripter

Share this post


Link to post

It all went downhill when Borland decided that function return values were actually var parameters. Which means that in the case of managed types they get initialized by the caller. 

 

A function return value really should have pass by value callee to caller semantics. 

Share this post


Link to post

I don't have the source at hand, but Embarcadero said that is is "too difficult" to fix, because the initialization of that variable takes place in another compiler code part that actually doesn't know how the variable is used.

 

There is, however, absolutely no excuse that there is no compiler warning. Embarcadero itself stumbles upon these uninitialized return values. Here's an example: [RSP-18300] TJson.Format() outputs invalid JSON - Embarcadero Technologies

Edited by Der schöne Günther

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

×