digitalmars.D.learn - non-const reference to const instance of class
- Zhenya (9/9) Oct 10 2012 Hi!
- Jonathan M Davis (11/23) Oct 10 2012 const Foo and const(Foo) are the same thing. They both create a const
- Zhenya (3/35) Oct 10 2012 Thank you)
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?
Oct 10 2012
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
Oct 10 2012
On Wednesday, 10 October 2012 at 17:35:48 UTC, Jonathan M Davis wrote:On Wednesday, October 10, 2012 19:02:31 Zhenya wrote:Thank you)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
Oct 10 2012








"Zhenya" <zheny list.ru>