Hi Rcpp-devel -

In some of my code, I return an XPtr pointing to one C++ class (e.g. class A) to the R side, and then pass it back down to the C++ side in the constructor of another class (e.g. class B, which needs access to some methods in class A). If I rm() both class A and the pointer to it on the R side (or they otherwise both go out of scope), then the garbage collector calls the destructor of class A twice and attempts to free the memory twice.

Happens on OSX and Ubuntu with latest R and Rcpp. Is this intended behavior? If yes, what's a recommended workaround? I can go into more detail on why this is useful to my workflow if needed. Below is a minimal example. Best,

        Mike Shvartsman.

-----
library(Rcpp)
library(inline)

inc <- '
using namespace Rcpp;
class A{
    public:
        A();
        ~A();
        XPtr<A> getPtr();
};

XPtr<A> A::getPtr(){
    return(XPtr<A>(this));
}

A::A(){
    Rcout << "CTOR" << std::endl;
}

A::~A(){
    Rcout << "DTOR" << std::endl;
}

RCPP_MODULE(mod){
    class_<A>("A")
    .constructor()
    .method("getPtr", &A::getPtr)
    ;
}
'

func <- cxxfunction(signature(), include=inc, plugin='Rcpp')

mod <- Module('mod', getDynLib(func))


A <- mod$A

a <- new(A)
aPtr <- a$getPtr()
rm(a)
rm(aPtr)
gc()
-----

_______________________________________________
Rcpp-devel mailing list
Rcpp-devel@lists.r-forge.r-project.org
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

Reply via email to