Worst ideas/features in programming languages?
Timon Gehr
timon.gehr at gmx.ch
Tue Nov 9 16:37:37 UTC 2021
On 08.11.21 15:04, Atila Neves wrote:
> On Friday, 5 November 2021 at 21:22:12 UTC, victoroak wrote:
>> On Friday, 5 November 2021 at 17:02:05 UTC, Atila Neves wrote:
>>>
>>>> - @safe `void` initialization
>>>
>>> For what types? It doesn't compile for pointers, for instance, and I
>>> don't see why void initialising an int would be unsafe.
>>>
>>>> - .init
>>>
>>> Because?
>>>
>>
>> Well, I can't answer for him but `void` initialization and `.init`
>> makes it impossible to have any meaningful constraint on a type. And
>> some types may depend on these constraints to maintain safety.
>>
>> ```d
>> import std.stdio;
>>
>> struct LimitedInt(int min, int max)
>> {
>> @disable this();
>>
>> this(int number)
>> {
>> assert(number >= min);
>> assert(number <= max);
>> _number = number;
>> }
>>
>> private int _number;
>> }
>>
>> void main() @safe
>> {
>> LimitedInt!(1, 1000) x = void;
>> auto y = LimitedInt!(1, 1000).init;
>> writeln(x);
>> writeln(y);
>> }
>> ```
>>
>> It's `@safe` in this example but there's no way to enforce these
>> constraints when you have those.
>
> Interesting. Adding an invariant causes compilation to fail:
>
> ```
> foo.d(27): Error: variable `foo.main.x` `void` initializers for structs
> with invariants are not allowed in safe functions
> ```
>
>
Well, that makes some sense, but a struct can have an invariant without
actually having it spelled out explicitly in the source code.
Furthermore, adding contracts actually makes code less safe in -release
mode.
More information about the Digitalmars-d
mailing list