www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - const ref type as return value

reply "Oleg B" <code.viator gmail.com> writes:
[code]
import std.stdio;

struct A { int val; }

A a;

class X { const ref A func() { return a; } }

void main()
{
     auto x = new X;
     x.func().val = 5;
     writeln( a );
}
[/code]

in this case 'const' mean 'const method' and variable 'a' changed.

if write
[code]
class X { const(ref A) func() { return a; } }
[/code]

$ dmd -run crtr.d
crtr.d(7): Error: basic type expected, not ref
crtr.d(7): Error: found 'ref' when expecting ')'
crtr.d(7): Error: semicolon expected, not ')'
crtr.d(7): Error: Declaration expected, not ')'
crtr.d(7): Error: unrecognized declaration

Only one way I find for workaround this
[code]
alias const ref A crA;
class X { crA func() { return a; } }
[/code]

But I think should exist more elegant solution.
Nov 29 2013
parent "Namespace" <rswhite4 googlemail.com> writes:
On Friday, 29 November 2013 at 09:05:50 UTC, Oleg B wrote:
 [code]
 import std.stdio;

 struct A { int val; }

 A a;

 class X { const ref A func() { return a; } }

 void main()
 {
     auto x = new X;
     x.func().val = 5;
     writeln( a );
 }
 [/code]

 in this case 'const' mean 'const method' and variable 'a' 
 changed.

 if write
 [code]
 class X { const(ref A) func() { return a; } }
 [/code]
ref const(A) func() { return a; }
Nov 29 2013