title: Creating and destroying objects in Delphi
body: <p>I am new to Delphi and am trying to better understand object creation / freeing as I am used to the luxury of .NET's GC. I have two questions specifically:</p>
  
  <ol>
  <li><p>Let's assume I am setting a TDataSource as below. In .NET I wouldn't explicitly destroy the object as I am with adoQuery.Free. But I am assuming that with Delphi I need to free these objects. However, by destroying the adoQuery I am also setting the dataset to null. In this way adoQuery is meant to be a locally scoped variable to the function only with the datsource being retuned from the function. Therefore, how can I best handle this?</p>
  
  <pre><code>dataSrc := TDataSource.Create(nil);
  dataSrc.DataSet := adoQuery;
  dataSrc.Enabled := true;
  { adoQuery.Free; }
  cnt := DataSrc.DataSet.RecordCount;
  </code></pre></li>
  <li><p>I've been reading several suggestions when returning a variable from a function that the best thing to do is create the variable within the caller and pass it to the subroutine. Therefore, the signature to a function would look like:</p>
  
  <pre><code>AdoConnectionManager.GetResult(query : String; dataSrc: TDataSource) : TDataSource;
  Result := dataSrc;
  </code></pre></li>
  </ol>
  
  <p>This is unattractive to me. I'd prefer to have a new variable created within the subroutine and then returned back to the caller. However, this is something again I never really had to worry about with .NET GC and here I have to explicitly destroy the variable, right? </p>
  
  <p>Thanks!</p>