rcpp和move语义 [英] Rcpp and move semantic

查看:77
本文介绍了rcpp和move语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C ++ 中实现了一种算法,该算法返回大量元素作为输出。现在,我想在 Rcpp 中实现一个包装器,这样我就可以使用 R 来调用此函数。

I implemented an algorithm in C++ that returns as output a huge array of elements. Now, I would like to implement a wrapper in Rcpp so that I will be able to call this function by using R.

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

I specified in the Makevars file the following setting:


PKG_CXXFLAGS = -std = c ++ 11

PKG_CXXFLAGS = -std=c++11

以便可以使用C ++ 11版本。

So that I can use the C++11 version.

// [[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,则上述包装函数仍然有效,否则将创建一个新对象。

The above wrapper function remains efficient if the NumericMatrix is moved when returned by the function, otherwise a new object will be created.

Rcpp 是否利用了移动语义?如果不是,是否有任何变通办法来避免构建副本?

Does Rcpp exploit the move semantics? And if not, are there any workarounds to avoid the construction of the copy?

推荐答案


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

The above wrapper function remains efficient if the NumericMatrix is moved when returned by the function, otherwise a new object will be created.

...如果没有,是否有任何解决方法避免构建副本?

... And if not, are there any workarounds to avoid the construction of the copy?

我认为复制构造函数只会创建浅表副本,因此不应有任何副本。参见 Rcpp:如何确保NumericMatrix的深层副本?

I think that only a shallow copy is created by the copy constructor so there should not be any copy. See Rcpp: How to ensure deep copy of a NumericMatrix? and

  • https://github.com/RcppCore/Rcpp/blob/b3b0bea7403d9836397148fa310b86eb24923aba/inst/include/Rcpp/vector/Matrix.h#L74
  • which calls 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)
*/

这篇关于rcpp和move语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆