[fpc-pascal] Fwd: What to do to get new users

Nikolay Nikolov nickysn at gmail.com
Mon Oct 21 08:32:42 CEST 2024


On 10/21/24 5:37 AM, Hairy Pixels via fpc-pascal wrote:
>
> then isn’t Pascal’s requirement to predeclare uninitialized variables 
> the worst possible design? In C you can at least declare a variable 
> with its assignment in one step but with Pascal by design you can 
> always read uninitialized memory with the exception of arguments.
>
> Many bugs I’ve caused because I didn’t set the “result” of a function 
> for example. I wish they could make that an option to always set the 
> default value.
Free Pascal produces warning for uninitialized values and has an option 
to treat warnings as error. My advice is to compile your programs with -Sew
> FPC does nothing to help you manage memory so I would expect more leaks.

It's not nothing. There's:

0) built-in leak detection with the -gh compiler option

1) ansistrings, widestrings and dynarrays

2) record types (as opposed to class), which can live on the stack and 
have a pass-by-value semantics. FPC trunk supports advanced records, so 
you get C++-style copy constructors.

3) the object type also has pass-by-value semantics

4) interfaces are COM-like and reference counted by default. Every 
interface inherits from IUnknown and the compiler automatically inserts 
calls to AddRef() and Release() when a variable enters or leaves scope, 
or when assigning values, or when passing them as parameters. If your 
class is only accessed through interfaces, you can just do:

type

   TMyReferenceCountedClass = class(TInterfacedObject, 
IMyFirstInterface, IMySecondInterface, ...)

> Being able to declare classes on the stack and destroy automatically 
> automates away a big category of memory leaks right there.

You can't with classes, but you can with records, objects and static 
arrays, which are usually more appropriate in these cases.

When using classes, the proper way to use them is to design them with 
some sort of ownership relations between them. For example ClassA 
contains a ClassB, so ClassA is responsible for creating ClassB and 
destroying ClassB, when ClassA is destroyed. That's how 99% of the class 
memory management system works, and it's so easy. The fact that the 
ownerships are explicit, and easily seen (and not hidden like in C++'s 
RAII style) makes thinking about this and debugging it easy. Out of the 
languages that require manual memory management, I've written C, C++, 
Rust and Object Pascal. Object Pascal is the easiest of them all. C 
comes second, but it has some horrible flaws, like the char* strings, 
which are very difficult to use correctly and very bug-prone.

Nikolay
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20241021/e3861ac0/attachment-0001.htm>


More information about the fpc-pascal mailing list