Const initialization issue, looking for solution

Maxim Fomin maxim at maxim-fomin.ru
Wed May 29 06:21:19 PDT 2013


On Wednesday, 29 May 2013 at 12:36:19 UTC, Jakob Ovrum wrote:
> I need to be able to catch an exception that may have been 
> thrown during the initialization of `i`, but still have `i` be 
> const. I can't omit the variable because I *don't* want to 
> accidentally catch anything that transform() may have thrown.
>
> Note that the simple type const(int) is an example. This is 
> actually in highly generic code and the type may have mutable 
> indirection.

Fundamental issue here is that

const T t;

is almost useless, it is essentially immutable since you cannot 
change it and you cannot alias it. As such, it probably should be 
changed to a mutable object or an immutable one.

However, since const/mutable aliasing is allowed, you can do:

union U (T)
{
    const T ct;
    T mt;
}

because const doesn't mean that object would never change, you 
can mutate it through alias. From the opposite view, there is 
also no problem in reinterpeting a mutable object as const object 
(since mutables can be converted to const).

Depending on your mutable indirection situation this can work or 
may not.


More information about the Digitalmars-d mailing list