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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With