假设我们在 F# 中有一个 Matrix 类,并且您重载了 (+) 运算符。然后,我们将有这样的事情:
type Matrix(n : int, m : int) =
...
static member (+) (A : Matrix, B : Matrix) =
let res = new Matrix(A.Dim1, A.Dim2) // suppose A and B have the same dimension
... // compute here the sum
res
与 C/C++ 相比,我们会有这样的东西:
static const Matrix operator+(const Matrix& A, const Matrix& B)
{
Matrix res(A.Dim1(), A.Dim2());
... // compute here the sum
return res;
}
现在,请注意,在 F# 中,矩阵res
是在堆内存中分配的,而 C++ 版本是res
在堆栈内存中分配的。
到目前为止,一切都很好。观察当我们想要在两个版本中对 sum 运算的结果进行“引用”时会发生什么:
Matrix result = A + B; // deep copy in C++ (because res has to be destroyed after its return)
let result = A + B // shallow copy in F# (res was allocated in the heap memory)
我是否在这里遗漏了某些东西,或者由于浅拷贝和深拷贝行为,F# 中的 (+) 运算符最终比 C/C++ 中的对应运算符更有效?