Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot pass by reference in D language

I have a constructor inside the class testclass

@safe public nothrow this(ref Socket socket) {
    // Inside class modulename.classname
    this.socket = socket;
}

When I initialize an object of this type in my main method however, I got a few compile errors.

void main() {
    auto variablename = new modulename.classname(
        cast(Socket) new TcpSocket() // main.d line 5
    );
}

Errors:

main.d(5): Error: constructor testmodule.testclass.this (ref 
Socket socket) is not callable using argument types (Socket)
main.d(5): Error: no constructor for testclass

Why cannot I pass the socket by reference?

like image 961
Jeroen Avatar asked Feb 27 '26 09:02

Jeroen


1 Answers

you shouldn't need to pass classes by ref

classes are kept by reference by default (to avoid the slicing problem when inheriting) so you are only passing a pointer in both cases anyway

the problem in your code is that cast(Socket) new TcpSocket() is a rvalue which can't be assigned to and thus cannot be passed by ref

like image 128
ratchet freak Avatar answered Mar 02 '26 15:03

ratchet freak