November 29, 2013 const ref type as return value | ||||
|---|---|---|---|---|
| ||||
[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.
| ||||
November 29, 2013 Re: const ref type as return value | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Oleg B | 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; }
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply