SystemVerilog this 关键字:引用当前对象

this 是 class 内指向当前对象的句柄。它最常用于解决参数名与成员名冲突,也可用于把当前对象作为参数传递。

1. 区分同名变量

1
2
3
4
5
6
7
class packet;
bit [31:0] addr;

function void set(bit [31:0] addr);
this.addr = addr; // 成员 = 参数
endfunction
endclass

不加 this 时,addr = addr 只是参数自赋值,成员保持默认值。

2. 传递当前句柄

1
2
3
4
5
class node;
function void register(scope s);
s.add(this); // 把自身交给容器
endfunction
endclass

3. 链式调用

1
2
3
4
function packet set_addr(bit [31:0] a);
addr = a;
return this; // 支持 p.set_addr(1).set_data(2)
endfunction

4. 常见误区

  1. 认为 this 会创建新对象:它只是引用。
  2. 在静态方法中写 this:非法。
  3. 用 this 比较对象内容:this == other 比较句柄,不是字段。

小结

this 解决“我在说谁”的问题。同名遮蔽、传递自身、链式返回是三个最实用的场景。

参考文献:ChipVerify SystemVerilog Tutorial — SystemVerilog ‘this’ keyword 章节(https://chipverify.com/systemverilog/systemverilog-this-keyword)。本文为原创中文讲解。