www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - non-const reference to const instance of class

reply "Zhenya" <zheny list.ru> writes:
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
parent reply "Jonathan M Davis" <jmdavisProg gmx.com> writes:
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
parent "Zhenya" <zheny list.ru> writes:
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)
Oct 10 2012