Is there a way to make a class variable visible but constant to outsiders, but changeable (mutable) to the class itself?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed May 25 05:10:14 PDT 2016
On 5/24/16 6:47 PM, Jonathan M Davis via Digitalmars-d-learn wrote:
> On Tuesday, May 24, 2016 18:28:44 Meta via Digitalmars-d-learn wrote:
>> On Tuesday, 24 May 2016 at 15:07:55 UTC, Jonathan M Davis wrote:
>>> On Tuesday, May 24, 2016 10:10:16 Steven Schveighoffer via
>>>
>>> Digitalmars-d-learn wrote:
>>>> A while ago, I discovered that this works.
>>>>
>>>> class C {
>>>>
>>>> union
>>>> {
>>>>
>>>> private int _my_var;
>>>> public const int my_var;
>>>>
>>>> }
>>>> void do_something() { _my_var = 4; }
>>>>
>>>> }
>>>
>>> Yeah. That's basically what Rebindable does, though in its
>>> case, it's not really allowing you to mutate any data, just
>>> what the reference refers to. Regardless, it does seem like a
>>> hole in the type system.
>>>
>>> - Jonathan M Davis
>>
>> I don't believe so. H. S. Teoh recently fixed a definite bug when
>> you have something like:
>>
>> struct S
>> {
>> union
>> {
>> int n1;
>> immutable int n2;
>> }
>> }
>>
>> But I'm pretty sure the case where n2 is const was purposely not
>> fixed as it doesn't break the type system. The value of a const
>> variable can be changed at any time out from under you, so a
>> union of a mutable and const int does not break any type system
>> guarantees.
>
> Except that int is a _value_ type, not a reference type. So, unions aside,
> once you've declared
>
> const foo = 42;
>
> it's impossible for the value of foo to change, and there's no real
> difference between
>
> const foo = 42;
>
> and
>
> immutable foo = 42;
>
> typeof(foo) will give you const in one case and immutable in the other, but
> effectively, they're identical.
But this isn't that. That's a declaration with an initializer.
There is a difference between:
struct S
{
const foo = 42;
}
and
struct S
{
const int foo;
}
-Steve
More information about the Digitalmars-d-learn
mailing list