title: Delphi function return class object
body: <p>In addition to <a href="https://stackoverflow.com/questions/45872925/delphi-error-while-returning-tlist">this</a> question I have made some tests and researches on the docwiki. My conclusion is that this kind of code should work without memory leaks:</p>
  
  <pre><code>function testResultObject: TClassA;
  begin
   Result := TClassA.Create;
   Result.DoSomething;
  end;
  </code></pre>
  
  <p>And then somewhere I can call the above code in this manner:</p>
  
  <pre><code>var k: TClassA;
  begin
  
   k := testResultObject;
   try
    //code code code
   finally
    k.Free;
   end;
  
  end;
  </code></pre>
  
  <p>As Remy suggested in the answer it's better to avoid this way of doing things and instead use something like <code>testResultObject(x: TClassA): boolean</code>. In this case the return true/false can tell me if everything went fine and I am passing an object already created.</p>
  
  <p>Look at this code:</p>
  
  <pre><code>function testResultObject: TClassA;
  begin
  
   Result := TClassA.Create;
  
   try
    Result.DoSomething;
   except
    Result.Free;
   end;
  
  end;
  </code></pre>
  
  <p>The problem with the first version above of the function is that <code>DoSomething</code> could raise an exception and if so I'll leak memory. Can the second implementation with <code>try-except</code> be a solution? For sure later I'll have to check if the result is assigned or nil.</p>
  
  <p>I agree that (as already said above) the <code>testResultObject(x: TClassA): boolean</code> would be better. I was just wondering if the return-a-class function way could be fixed as I've written.</p>