www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Returning references to const data from const methods

reply Leonard Dahlmann <leo.dahlmann gmail.com> writes:
How could I do the following?

I'm getting this error message:
test.d(15): Error: c.gimme can only be called on a mutable object

<code>
class Foo
{
	uint x;

	const (const(uint)*) gimme()
	{
		return &x;
	}
}

void main()
{
	const(Foo) c = new Foo;

	const(uint)* x = c.gimme(); // line 15
}
</code>
Jun 18 2007
next sibling parent "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Leonard Dahlmann" <leo.dahlmann gmail.com> wrote in message 
news:f57tbr$p41$1 digitalmars.com...
 How could I do the following?

 I'm getting this error message:
 test.d(15): Error: c.gimme can only be called on a mutable object

 <code>
 class Foo
 {
 uint x;

 const (const(uint)*) gimme()
 {
 return &x;
 }
 }

 void main()
 {
 const(Foo) c = new Foo;

 const(uint)* x = c.gimme(); // line 15
 }
 </code>

Don't have the D2 compiler here, but shouldn't that be invariant const(uint)* gimme() ?
Jun 19 2007
prev sibling parent reply Christian Kamm <kamm.incasoftware shift-at-left-and-remove-this.de> writes:
 How could I do the following?
 
 <code>
 class Foo
 {
 uint x;
 
 const (const(uint)*) gimme()
 {
 return &x;
 }
 }

I think you have to remove the outermost parentheses. Probably the compiler thinks the return type is const(const(uint)*) for a normal method and not const(uint)* for a const method. This works for me: alias const(uint)* returnType; const returnType gimme() {...} But this fails to compile: const const(uint)* gimme() {...} Cheers, Christian
Jun 19 2007
parent Deewiant <deewiant.doesnotlike.spam gmail.com> writes:
Christian Kamm wrote:
 This works for me:
 
 alias const(uint)* returnType;
 const returnType gimme() {...}
 
 But this fails to compile:
 
 const const(uint)* gimme() {...}
 
 Cheers,
 Christian

You might want to file a bug for that: an alias should behave the same way as the base type. I'm not sure which behaviour is correct, but they should at least be the same. -- Remove ".doesnotlike.spam" from the mail address.
Jun 19 2007