SystemVerilog中静态变量和静态方法的理解
静态变量
1.与硬件领域例如module,interface不同的是,在class中声明的变量其默认类型为动态变量,即其声明周期在仿真开始后的某时间点开始到某时间点结束。具体来讲,其声明周期开始于对象创建,终于对象销毁。
2.如果使用关键字static来声明class内的变量时,则其为静态变量。静态变量的生命开始于编译阶段,贯穿于整个仿真阶段。
3.如果在类中声明了静态变量,那么可以直接引用该变量class::var,或者通过例化对象引用object.var。类中的静态变量声明以后,无论例化多少个对象,只可以共享一个同名的静态变量,因此类的静态变量在使用时需要注意共享资源的保护。
class Transaction;
static int count = 0;
int id;
function new();
id = count++;
endfunction
endclass
Transaction t1, t2;
initial begin
t1 = new();
t2 = new();
$display("second id= %d, count=%d", t2.id, t2.count);//或者Transaction::count
静态方法
1.类似于静态变量,在class中定义的方法默认类型是动态方法,而我们也可以通过关键词static修改其类型为静态方法。
2.静态方法内可以声明并使用动态变量,但是不能使用类的动态成员变量。原因是因为在调用静态方法时,可能并没有创建具体的对象,也因此没有为动态成员变量开辟空间,因此在静态方法中使用类的动态成员变量时禁止的,可能会造成内存泄漏,但是静态方法可以使用类的静态变量,因为静态方法同静态变量一样在编译阶段就已经为其分配好了内存空间。
class Transaction;
static Config cfg;
static int count = 0;
int id;
static function void display_statics();
$display("Transaction cfg.mode=%s, count=%0d", cfg.mode.name(), count);
endfunction
endclass
Config cfg;
intial begin
cfg = new(MODE_ON);
Transaction::cfg = cfg;//静态变量赋值
Transaction::display_statics();//调用静态方法
end
浙公网安备 33010602011771号