RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TObjectStack Class

Last in, first out stack of objects.

Pascal
TObjectStack<T: class> = class(TStack<T>);
C++
template <T: class>
class TObjectStack : public TStack<T>;

TObjectStack represents a last in, first out stack of objects of the same type. It is of arbitrary size, expanding as needed. You can push nil on the stack. 

TObjectStack is a TStack with the capability of automatically freeing object entries when they are removed from the stack. When a TObjectStack is instantiated, an AOwnsObjects parameter specifies whether the stack owns the stack entries. If the entry is owned, when the entry object is removed from the stack, the entry object is freed. 

The OwnsObjects property gets or sets object ownership.  

Delphi Examples: 

 

{
This example demonstrates the usage of the generic TObjectStack class.
}
type
  { Declare a new object type }
  TNewObject = class
  private
    FName: String;

  public
    constructor Create(const AName: String);
    destructor Destroy(); override;
  end;

{ TNewObject }

constructor TNewObject.Create(const AName: String);
begin
  FName := AName;
end;

destructor TNewObject.Destroy;
begin
  { Show a message whenever an object is destroyed }
  MessageDlg('Object "' + FName + '" was destroyed!', mtInformation, [mbOK], 0);
  inherited;
end;

procedure TForm3.Button1Click(Sender: TObject);
var
  Stack: TObjectStack<TNewObject>;
  Button: TButton;
begin
  { Create a new stack }
  Stack := TObjectStack<TNewObject>.Create();

  { Set the OwnsObjects to true - the stack will free them automatically }
  Stack.OwnsObjects := true;

  { Push some items up the stack }
  Stack.Push(TNewObject.Create('One'));
  Stack.Push(TNewObject.Create('Two'));
  Stack.Push(TNewObject.Create('Three'));

  {
    Pop an instance of TNewObject class. Destructor
    show be called because we have set the OwnsObjects
    to true!
  }
  Stack.Pop();

  { Destroy the stack completely - more messageboxes will be shown }
  Stack.Free;
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!