toshi-san
toshi-san

Reputation: 353

Does converting vectors between Rcpp and C++ (using Rcpp::as or Rcpp::wrap) create a new vector and copy elements?

In my understanding, converting vectors between Rcpp and C++ creates new vectors as follows. Is my understanding right?

When converting an Rcpp vector to a C++ vector, we use Rcpp::as<T>() (e.g. Rcpp::as<std::string> for Rcpp::CharacterVector). std::vector<std::string> is created, and the original Rcpp elements are copied into the C++ vector as std::string. This means that modifying the newly created C++ vector elements does not affect the original Rcpp vector elements.

When converting a C++ vector to an Rcpp vector, we use Rcpp::wrap(). Rcpp vector with the corresponding type is created, and the C++ elements are copied into the Rcpp vector as Rcpp objects. This means that modifying the newly created Rcpp vector elements does not affect the original C++ vector elements.

Upvotes: 4

Views: 794

Answers (1)

coatless
coatless

Reputation: 20746

Correct, the following functions perform conversions:

// conversion from R to C++
Rcpp::as<T>();
// conversion from C++ to R
Rcpp::wrap();

In short, moving data from an Rcpp object into a C++ vector and vice versa causes a copy to be made. This has been explained a bit here:

Declare a variable as a reference in Rcpp

For more on the templating, please see the Rcpp Extending vignette.

Details on cost from an Rcpp::*Vector to std::vector<T> can be found here:

Should I prefer Rcpp::NumericVector over std::vector?

One way to avoid the copy is to re-use memory if possible. This is hinted at here:

Deciding between NumericVector and arma::vec in Rcpp

Upvotes: 8

Related Questions