const(Class) is mangled as Class const* const

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sun Mar 26 08:29:02 PDT 2017


On Sunday, March 26, 2017 14:51:28 Namespace via Digitalmars-d wrote:
> On Sunday, 26 March 2017 at 14:30:00 UTC, deadalnix wrote:
> > On Sunday, 26 March 2017 at 10:43:11 UTC, Benjamin Thaut wrote:
> >> As you see from the above example D mangles the getClassConst
> >> as a "Class const * const" instead of a "Class const *"
> >> ("YAQEBV" vs "YAPEBV"). Is this expected behavior?
> >
> > It's consistent. D's const is transitive, and D doesn't allow
> > you to specify const on the indirection of a reference type. So
> > there is no problem on the C++ mangling side of things, but,
> > arguably, there is one in D's sementic, that isn't new.
> >
> > Something like differentiating "const(C) i" and "const C i" may
> > be a good idea.
>
> After reading your post, I wonder: How could I translate the
> following C++ code to D?
>
> ----
> int a = 2;
> int* const p = &a;
> ----

You don't. Once part of a type is const, everything inside it is const. So,
if a pointer is const, everything it points to is const. You can have the
outer part be mutable with the inner part be const, but not the other way
around. D's const can do tail-const, but it can't do head-const.

Now, while you can't use const to make the pointer const and what it points
to mutable, you _can_ make the the pointer read-only while still having what
it points to be fully mutable by putting it in a struct which restricts
write-access to the pointer. I believe that that's essentially what
std.experimental.typecons.Final is supposed to do.

Personally, I don't think that the fact that you can't use const for
head-const in D is really a loss, since it's almost never what you want.
Tail-const is _way_ more useful. But it is true that by making D's const
fully transitive, there are variations of constness that C++ can do that D
can't. immutable pretty much forces that though, and it does simplify the
language.

- Jonathan M Davis



More information about the Digitalmars-d mailing list