Cannot pass by reference

Ali Çehreli acehreli at yahoo.com
Sat Nov 16 08:34:31 PST 2013


On 11/16/2013 06:08 AM, Jeroen Bollen wrote:
> I cannot seem to pass values to functions by referece.
>
> ----------------------------------------------------------------------------------
>
>      @safe public nothrow this(ref Socket socket) {
>          // Inside class modulename.classname
>          this.socket = socket;
>      }
> ----------------------------------------------------------------------------------
>
>      void main() {
>          auto variablename = new modulename.classname(
>              cast(Socket) new TcpSocket() // main.d line 5
>          );
>      }
> ----------------------------------------------------------------------------------
>
>
> This code gives me a compile error:
>
> main.d(5): Error: constructor modulename.classname.this (ref Socket
> socket) is not callable using argument types (Socket)
> main.d(5): Error: no constructor for classname
>
> Why is that?

First, just a reminder: Classes in D are reference types so in most 
cases there is no need for ref; it already is a reference to the actual 
object.

Assuming that you really want to pass the class reference by ref, so 
that the function wants to change the actual object, the following workes:

class C
{}

class D1 : C
{}

class D2 : C
{}

void foo(ref C c)
{
     // Change the caller's object
     c = new D2();
}

void main()
{
     C c = new D1();
     foo(c);
}

The problem with your example is that unlike main.c in my example, what 
you pass is an rvalue, which may not be bound to the ref parameter.

So, if you didn't want ref to begin with, just drop it.

If you really wanted to change the caller's object, then provide an 
lvalue (e.g. a regular local variable) so that it can be changed.

Ali



More information about the Digitalmars-d-learn mailing list