'the address of Self in constructor in freepascal?
Below is the output of test code.
Why are the addresss of instance(@a) and the address of Self(@Self) in constructor different?
I think both should be the same. The addresss of class instance and the address of this in constructor are same in c++.
Is it possible to get the address equal to the addresss of instance(@a) in constructor?
Lazarus 2.2.0 64bit for windows.
@Self=00000000013FFDC8
@a=00000000013FFE38
a.i=3
a_ptr^.i=3
ga_ptr^.i=5872 << invalid value
unit unitmain;
{$mode ObjFPC}{$H+}
interface
uses
Classes, SysUtils;
type
ClassA = class
public
constructor Create(i : Integer);
var
i : Integer;
end;
PClassA = ^ClassA;
var
ga_ptr : PClassA;
procedure TestSelfAddr();
implementation
constructor ClassA.Create(i : Integer);
begin
Self.i := i;
ga_ptr := @Self;
Writeln(Format('@Self=%P', [@Self]));
end;
procedure TestSelfAddr();
var
a : ClassA = nil;
a_ptr : PClassA = nil;
begin
a := ClassA.Create(3);
a_ptr := @a;
Writeln(Format('@a=%P', [@a]));
Writeln(Format('a.i=%d', [a.i]));
Writeln(Format('a_ptr^.i=%d', [a_ptr^.i]));
Writeln(Format('ga_ptr^.i=%d', [ga_ptr^.i])); // << invalid value
end;
end.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
