This language bar is your friend. Select your favorite languages!

Idiom #209 Type with automatic deep deallocation

Declare a type t which contains a string s and an integer array n with variable size, and allocate a variable a of type t. Allocate v.s and v.n and set them to the values "Hello, world!" for s and [1,4,9,16,25], respectively. Deallocate v, automatically deallocating v.s and v.n (no memory leaks).

class T:
    def __init__(self, s, n):
        self.s = s
        self.n = n
        return

v = T('hello world', [1, 4,  9, 16, 25])
del v
  type t
    character(len=:), allocatable :: c
    integer, dimension(:), allocatable :: n
  end type t
  type(t), allocatable :: v

  allocate (v)
  v%s = 'Hello, world!'
  v%n = [1,4,9,16,25]

  deallocate (v)
type
  TDynIntArray = array of integer;
  TT = record
    s: string;
    n: TDynIntArray;
  end;
  PTT = ^TT;

var
  v: PTT;
begin
  v := New(PTT);
  v^.s := 'Hello world';
  v^.n := TDynIntArray.Create(1,4,9,16,25);
  Dispose(v);
end.
use Moops;
class T {
    has 's', is => 'ro', isa => Str;
    has 'n', is => 'ro', isa => ArrayRef[Int];
}

{
    my $v = T->new(s => 'Hello, world!', n => [1,4,9,16,25]);
    # deallocation happens at closing brace, see explanation
}

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

tkoenig