Thread overview | |||||
---|---|---|---|---|---|
|
October 10, 2012 non-const reference to const instance of class | ||||
---|---|---|---|---|
| ||||
Hi! I thought that this should compile: class Foo{} const(Foo) foo = new Foo;// the same that const Foo foo? foo = new Foo; but compiler say that foo is const reference and it can't modify it. It is normally?If yes,how can I declare non-const reference to const instance of class? |
October 10, 2012 Re: non-const reference to const instance of class | ||||
---|---|---|---|---|
| ||||
Posted in reply to Zhenya | On Wednesday, October 10, 2012 19:02:31 Zhenya wrote:
> Hi!
>
> I thought that this should compile:
> class Foo{}
>
> const(Foo) foo = new Foo;// the same that const Foo foo?
> foo = new Foo;
>
> but compiler say that foo is const reference and it can't modify
> it.
> It is normally?If yes,how can I declare non-const reference to
> const instance of class?
const Foo and const(Foo) are the same thing. They both create a const reference to const data. This is in contrast to a pointer where const Bar* and const(Bar)* are different. With a reference, there is no way to indicate that the object is const but not the reference. The type system just doesn't support the idea of a class object existing separately from a reference, so there's no way to make that distinction.
If you want to have a mutable reference to a const object, then you need a wrapper around the reference where the wrapper is mutable but the reference isn't. std.typecons.Rebindable does this. It's what you should use.
- Jonathan M Davis
|
October 10, 2012 Re: non-const reference to const instance of class | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jonathan M Davis | On Wednesday, 10 October 2012 at 17:35:48 UTC, Jonathan M Davis wrote:
> On Wednesday, October 10, 2012 19:02:31 Zhenya wrote:
>> Hi!
>>
>> I thought that this should compile:
>> class Foo{}
>>
>> const(Foo) foo = new Foo;// the same that const Foo foo?
>> foo = new Foo;
>>
>> but compiler say that foo is const reference and it can't modify
>> it.
>> It is normally?If yes,how can I declare non-const reference to
>> const instance of class?
>
> const Foo and const(Foo) are the same thing. They both create a const
> reference to const data. This is in contrast to a pointer where const Bar* and
> const(Bar)* are different. With a reference, there is no way to indicate that
> the object is const but not the reference. The type system just doesn't
> support the idea of a class object existing separately from a reference, so
> there's no way to make that distinction.
>
> If you want to have a mutable reference to a const object, then you need a
> wrapper around the reference where the wrapper is mutable but the reference
> isn't. std.typecons.Rebindable does this. It's what you should use.
>
> - Jonathan M Davis
Thank you)
|
Copyright © 1999-2021 by the D Language Foundation