将 this 指针传递给构造函数

Passing the this pointer to a constructor

我正在尝试用 D 编写一个涉及 Server class 的程序,它在新客户加入时创建新的 Client 对象。 我想在客户端创建时将服务器对象传递给它们, 但是当稍后我尝试从客户端访问 Server 对象时,我的程序停止并显示 错误代码-11。我用谷歌搜索了一下,但一无所获。

我已在以下代码段中成功地重新创建了此行为:

import std.stdio;



class Server
{
public:
    int n;
    Client foo() //Foo creates a new client and passes this to it
    {return new Client(this);}
}

class Client
{
public:
    this(Server sv) //Constructor takes Server object
    {sv=sv;}
    Server sv;
    void bar() //Function bar tries to access the server's n
    {writeln(sv.n);}
}

void main()
{
Server s = new Server; //Create a new server object
Client c = s.foo(); //Then ask for a client
//c.sv=s; //!!!If I leave this line in the source then it works!!!
sv.n=5; //Set it to a random value
c.bar(); //Should print 5, but instead crashes w/ error -11
}

如果我取消注释 c.sv=s 行,那么它就神奇地起作用了,我不明白。

那么为什么如果我在构造函数中设置 sv 然后它崩溃,但如果我稍后设置它然后它工作?

编辑:writeln(sv) 添加到 bar 函数会打印 null,因此可能会导致崩溃。但是为什么是null?

{sv=sv;}

这一行是错误的。它设置本地 sv,而不是 class 实例。尝试 this.sv = sv; 而不是将实例成员设置为本地。

编辑:因为您从未设置实例变量,所以它保持未初始化状态 - 默认为 null。