Rcpp and move semantic

Rcpp and move semantic

本文关键字:semantic move and Rcpp      更新时间:2023-10-16

我在C++中实现了一个算法,该算法返回一个巨大的元素数组作为输出。现在,我想在Rcpp中实现一个包装器,以便能够使用R调用此函数。

我在Makevars文件中指定了以下设置:

PKG_CXXFLAGS=-std=c++11

这样我就可以使用C++11版本了。

// [[Rcpp::export]]
NumericMatrix compute(int width, int height)
{
  vector<data_t> weights(width * height);
  compute_weights(weights);
  NumericMatrix mat(height, width);
  copy(begin(weights), end(weights), mat.begin());
  return mat;
}

如果NumericMatrix在函数返回时被移动,则上述包装函数仍然有效,否则将创建一个新对象。

Rcpp是否利用了移动语义?如果没有,有没有办法避免构建副本?

如果NumericMatrix在函数返回时被移动,则上述包装函数仍然有效,否则将创建一个新对象。

如果没有,有没有办法避免构建副本?

我认为副本构造函数只创建了一个浅副本,所以不应该有任何副本。请参阅Rcpp:如何确保NumericMatrix的深度复制?和

  • https://github.com/RcppCore/Rcpp/blob/b3b0bea7403d9836397148fa310b86eb24923aba/inst/include/Rcpp/vector/Matrix.h#L74
  • 哪个调用https://github.com/RcppCore/Rcpp/blob/b3b0bea7403d9836397148fa310b86eb24923aba/inst/include/Rcpp/vector/Vector.h#L62-L67

这个例子也证实了这一点

#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector allocate_the_vec(R_xlen_t n_ele){
  Rcpp::NumericVector out(n_ele);
  return out;
}
/*** R
# got 16 GB ram on my laptop. 3 x 7 is an issue but 2 x 7 is not
how_large <- as.integer(7 * 10^9 / 8)
the_large_vec_1 <- allocate_the_vec(how_large)
object.size(the_large_vec_1)
the_large_vec_2 <- allocate_the_vec(how_large)
*/