[Rcpp-devel] shallow/deep copy
zhongyi-yuan at uiowa.edu
Wed Aug 31 17:49:42 CEST 2011
Thank you for your answer. It becomes much clearer to me now.
In particular, I really appreciate your "P.S.". Quite useful for beginners
On Wed, Aug 31, 2011 at 1:40 AM, Darren Cook <darren at dcook.org> wrote:
> > NumericVector x = as<NumericVector>(x_); ( Btw, this is exactly the same
> > NumericVector x(x_), both resulting in a shallow copy, isn't it? )
> > 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.
> 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)
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Rcpp-devel