Rcpp 中值和引用参数之间的差异

Difference between value and reference args in Rcpp

本文关键字:之间 参数 引用 Rcpp      更新时间:2023-10-16

考虑以下 2 个函数:

library(Rcpp)
cppFunction("NumericVector func1(NumericVector &x)
{
    for (int i = 0; i < x.length(); i++)
        x[i] = x[i] * 2;
    return x;
}")

cppFunction("NumericVector func2(NumericVector x)  // no &
{
    for (int i = 0; i < x.length(); i++)
        x[i] = x[i] * 2;
    return x;
}")

唯一的区别是func1x作为引用参数,而func2将其作为值。如果这是常规C++,我会将其理解为func1允许更改调用代码中x的值,而这不会发生在func2中。

然而:

> x <- 1:10/5  # ensure x is numeric, not integer
> x
 [1] 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0
> func1(x)
 [1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0
> x
 [1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0  # x in calling env has been modified

> x <- 1:10/5  # reset x
> x
 [1] 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0
> func2(x)
 [1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0
> x
 [1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0  # x is also modified
因此,就

对论点的副作用而言,看起来func1func2的行为方式相同。

这是什么原因呢?通常,通过引用还是按值将参数传递给 Rcpp 函数更好?

首先,两个函数都返回一个未分配给任何变量的NumericVector,因此未被使用。下面的代码等效于您拥有的代码,因为无论如何您都会丢弃返回的NumericVector

cppFunction("void func1(NumericVector& x)
            {
            for (int i = 0; i < x.length(); i++)
            x[i] = x[i] * 2;
            }")

cppFunction("void func2(NumericVector x)  // no &
            {
            for (int i = 0; i < x.length(); i++)
            x[i] = x[i] * 2;
            }")
x <- 1:10/5
func1(x)
print(x)
x <- 1:10/5
func2(x)
print(x)

其次,NumericVector在C++函数中充当指针。指针为您提供存储值的地址,并且为了能够更改该地址的值,您只需要知道地址,但不需要修改地址本身的能力。因此,按值传递指针或按引用传递指针没有区别。

此线程包含有关NumericVector行为的有用知识:

我应该更喜欢 Rcpp::NumericVector 而不是 std::vector 吗?

下面的程序演示了C++中的相同行为。

#include <iostream>
void func1(double* a) // The pointer is passed by value.
{
    for (int i=0; i<3; ++i)
        a[i] *= 2;
}
void func2(double*& a) // The pointer is passed by reference.
{
    for (int i=0; i<3; ++i)
        a[i] *= 2;
}
void print(double* a)
{
    std::cout << "Start print:" << std::endl;
    for (int i=0; i<3; ++i)
        std::cout << a[i] << std::endl;
}
int main()
{
    double* x = new double[3];
    // Set the values with 1, 2, and 3.
    for (int i = 0; i<3; ++i)
        x[i] = i+1;
    print(x);
    func1(x);
    print(x);
    // Reset the values with 1, 2, and 3.
    for (int i = 0; i<3; ++i)
        x[i] = i+1;
    // This block shows the same behavior as the block above.
    print(x);
    func2(x);
    print(x);
    delete[] x;
}