Structs by ref in D2

Jesse Phillips jessekphillips at gmail.com
Thu Aug 20 22:05:56 PDT 2009


On Thu, 20 Aug 2009 18:15:07 -0400, bearophile wrote:

> This post is about D2 compiler/language. Is the following code supposed
> to be wrong in D2? (and if so, then why?)
> 
> import std.c.stdio: printf;
> 
> struct S { int x, y; }
> 
> S produce() {
>     S s = S(10, 20);
>     return s;
> }
> 
> void show(ref S s) {
>     printf("%d %d\n", s.x, s.y);
> }
> 
> void main() {
>     show(produce());
> }
> 
> 
> That code works in D1.042, while DMD V.2.031 gives the errors:
> test.d(10): Error: function temp.show (ref S s) does not match parameter
> types (S) test.d(10): Error: produce() is not an lvalue
> 
> 
> After a gentle suggestion by Kirk McDonald I have also tried the
> following signatures, with similar error messages: void show(ref
> const(S) s) {
> void show(const ref S s) {
> 
> passing locally-defined structs by ref is handy (the LDC compiler is
> currently able to do it, as older D1 compilers too).
> 
> Bye,
> bearophile

Note that I don't know much about what I'm saying :)

This is probably related to an early conversation, not sure which one, 
but if I recall correctly this is supposed to be an error.

The problem is that produce() is returning a temporary variable which 
would have no affect if modified. The idea is that such modification is 
unintended and should be flag as an error.

If you are interested in performance than I'd think void show(const S s) 
should be reasonable, but that could have threading issues if the 
compiler makes it a reference.


More information about the Digitalmars-d-learn mailing list