Safety is not what you think
Paul Backus
snarwin at gmail.com
Tue Jan 30 15:38:26 UTC 2024
On Tuesday, 30 January 2024 at 02:05:23 UTC, user1234 wrote:
> I want to share a stupid program to show you that D safety is
> more complex than you might think:
>
> ```d
> module test;
>
> void test() @safe
> {
> int i;
> int b = (*&(*&++i))++;
> }
>
> void main() @safe
> {
> test();
> }
> ```
>
> I'm not showing a deficiency of D, that program is undeniably
> safe ;)
I'm surprised `&++i` even compiles in the first place, but
looking at [the spec][1], it seems to be intentional:
> The following expressions, and no others, are called lvalue
> expressions or lvalues:
>
> [...]
> 4. the result of the following expressions:
> * built-in unary operators + (when applied to an lvalue), *,
> ++ (prefix only), -- (prefix only);
Testing it out, the address you get is the same as `&i`.
This definitely isn't allowed in C or C++. I wonder what the
rationale is for having this behavior in D?
[1]: https://dlang.org/spec/expression.html
More information about the Digitalmars-d-learn
mailing list