[Rcpp-devel] shallow/deep copy
Darren Cook
darren at dcook.org
Wed Aug 31 08:40:02 CEST 2011
> NumericVector x = as<NumericVector>(x_); ( Btw, this is exactly the same as
> NumericVector x(x_), both resulting in a shallow copy, isn't it? ) produces
> a shallow copy, while
> vector<double> x = as< vector<double> >(x_); produces a deep copy.
>
> Is it because for NumvericVector the as() function returns the address of
> x_? But why does it work differently for vector<double>?
Hello Zhongyi,
I think if you put the namespaces on, explicitly, it becomes clearer:
Rcpp::NumericVector x = as<Rcpp::NumericVector>(x_);
std::vector<double> x = as< std::vector<double> >(x_);
(I'm assuming x_ is the parameter being passed in from R.)
x_ is effectively a pointer to a block of memory owned by R.
Rcpp classes are just wrappers around that same pointer. Hence a shallow
copy is possible.
std::vector is a block of memory allocated and owned by your C++ code,
so the bytes need to be physically copied over.
Darren
P.S. You'll see a lot of C++ code that keeps the std:: namespace
definition in, rather than a using namespace std; at the top of the file.
It adds 5 characters each time, but on the other hand it *only* adds 5
characters each time.
I don't know who invented this convention, or all the reasons it is
good, but I personally do it that way, without regret.
--
Darren Cook, Software Researcher/Developer
http://dcook.org/work/ (About me and my work)
http://dcook.org/blogs.html (My blogs and articles)
More information about the Rcpp-devel
mailing list