anyway to set a const object after the fact?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Oct 30 17:40:02 UTC 2018


On Tuesday, October 30, 2018 2:18:15 AM MDT Laurent Tréguier via 
Digitalmars-d-learn wrote:
> On Monday, 29 October 2018 at 21:50:32 UTC, aliak wrote:
> > Hi, so if you have this piece of code:
> >
> > struct C {
> >
> >   void f() {
> >
> >     string[] others;
> >     const string[] restArgs;
> >     foreach (i, arg; args) {
> >
> >       if (isValidArg(arg)) {
> >
> >         restArgs = args[i + 1 .. $];
> >         break;
> >
> >       }
> >       others ~= arg;
> >
> >     }
> >     // "others" is a list of args before the valid arg is
> >
> > encountered
> >
> >     // "restArgs" is a list that is the args after the valid arg
> >
> >   }
> >
> > }
> >
> > Is there anyway to set a const object after declaring it in the
> > above context?
> >
> > Cheers,
> > - Ali
>
> It looks like there is a Rebindable type for that in std.typecons
>
> : https://dlang.org/phobos/std_typecons.html#Rebindable

Rebindable is specifically intentended for class references, since D doesn't
really distinguish between the reference and what it's pointing to, making
it impossible to under normal circumstances to have a mutable reference to a
const object. On the other hand, you can easily have mutable arrays of const
objects. Using Rebindable is a really a hack (albeit a very necessary one
for some circumstances), and I would very much advise _against_ using it if
you don't need it. Historically, it tends to run into compiler bugs, because
it's trying to hack it's way around the type system, and if you're not
dealing with class references, there's probably a better way to handle the
problem.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list