Need some help on understanding following code. what is need for ref keyword for ref_dst in the following code ? why can’t simply pass the value to copy function where as I notice that whenever passing object ( after constructed) to another function/task to ref__ becomes not a requirement.
class Transaction;
bit [31:0] addr=100, data=16’hAAAA;
function void copy(ref Transaction ref_dst); // what is need for ref here ?
$display(“I’m in copy function\n”);
ref_dst=new();
ref_dst.addr = addr;
ref_dst.data = data;
endfunction
endclass
This was probably written by a C/C++ coder. There is no need for a ref argument here. It should be an output. (and the function is doing more of a clone, not just a copy.
There is almost never a need to pass a class variable by reference - it is already a reference to an object. You want to copy the value of the class handle that is constructed inside the function, and copy the handle to the class variable dst in the module when the function returns. The previous reply is incorrect: it is the handle to the object that gets passed through the argument, not the object itself.
And there is almost never a need to use ref arguments with a function. The only time you might consider passing by reference is when an argument is a large array or structure and you want to avoid having a local variable that needs to copy the entire array/struct for better performance. But accessing an argument by an indirect reference is more expensive than a direct local access. So if your function does a lot of accessing that argument, you will lose all the performance gain you were hope to get. So it’s best to use an input/output/inout argument in a function a let the compiler optimize the code for you.