Skip to content
Prev 5647 / 10988 Next

[Rcpp-devel] Module with vector of a class with inheritance, how to avoid slicing

but when I do 

res=new("Rcpp_vector_Of_father",1:10)
res[[1]]$WhoAmI()
res[[0]]$WhoAmI()

rm(res)
gc()

that crashes with gc()
R.



----- Mail original -----
De: "Robin Girard" <robin.girard at mines-paristech.fr>
?: "Romain Francois" <romain at r-enthusiasts.com>
Cc: rcpp-devel at lists.r-forge.r-project.org
Envoy?: Jeudi 4 Avril 2013 18:08:50
Objet: Re: [Rcpp-devel] Module with vector of a class with inheritance, how to avoid slicing

that works.... indeed :)
R.


----- Mail original -----
De: "Romain Francois" <romain at r-enthusiasts.com>
?: "Robin Girard" <robin.girard at mines-paristech.fr>
Cc: rcpp-devel at lists.r-forge.r-project.org
Envoy?: Jeudi 4 Avril 2013 17:58:42
Objet: Re: [Rcpp-devel] Module with vector of a class with inheritance, how to avoid slicing

Le 04/04/13 17:34, Robin Girard a ?crit :
I would just use new and delete, and likely combine this with some STL 
ness to make nicer looking code. Something like this perhaps:

     children* new_children1( double x){
         return new children1( x ) ;
     }

     vector_Of_father(Rcpp::NumericVector vec) : MyfatherList_(vec.size()){
         std::transform( vec.begin(), vec.end(), MyfatherList_.begin(), 
new_children ) ;
     }


Same for the destructor:

     template<typename T>
     void deleter( T* ptr ){ delete ptr; }

     ~vector_Of_father() {
         std::for_each( MyfatherList_.begin(), MyfatherList_.end(), 
deleter<father> ) ;
     };

Of course, with C++11 you could use lambdas instead of the new_children1 
and deleter functions, but that's another story.



Now, this design implies that the vector_Of_father class is repsonsible 
for the memory of its pointers. That's fine. But you need to keep this 
in mind for when you do stuff with the class, e.g. when you assign an 
element to the vector, make sure you delete the previous one, etc ...

Romain