<div dir="ltr"><div>I want to expose to R several C++ classes from a library with Rcpp modules.  I'm trying to imitate a similar set of Python modules that were made for the same library.</div><div><br></div><div>In Boost.Python, with .def it is possible to specify the return_value_policy.  Is it also possible to do this in a straight forward way with Rcpp modules when exposing C++ class methods?</div><div><br></div><div>The following simplified example illustrates a problem I face with using Rcpp modules.  When R deletes 'res', R crashes shortly after (a segfault?).  </div><div><br></div><div>With a Python module, this kind of problem apparently doesn't come about by setting in .def the following: <span style="color:rgb(0,0,0);font-family:monospace;font-size:12px;white-space:pre">return_value_policy<reference_existing_object>()</span> </div><div><br></div><div>Is there an easy way to get around this problem with Rcpp modules with minimal code?</div><div><br></div><div>#include <Rcpp.h></div><div>using namespace Rcpp;</div><div><br></div><div>class A {</div><div><br></div><div>  public:</div><div>    </div><div>    A(int x_) : x(x_){}</div><div><br></div><div>    int x;</div><div>};</div><div><br></div><div>class B {</div><div>  </div><div>  public:</div><div>    B():m_A(10) {}</div><div>  </div><div>    A get_an_A(){</div><div>      A an_A(3);</div><div>      return an_A;</div><div>    }</div><div>    A * get_member_A() { return & m_A; }</div><div>      </div><div>  private:</div><div>    A m_A;</div><div>};</div><div><br></div><div>RCPP_EXPOSED_CLASS(A)</div><div>RCPP_EXPOSED_CLASS(B)</div><div><br></div><div>RCPP_MODULE(AB_mod){</div><div>  using namespace Rcpp ;</div><div>  class_<A>("A")</div><div>   .constructor<int>()</div><div>   .field("x", &A::x)</div><div>  ;</div><div>  class_<B>("B")</div><div>   .constructor()</div><div>   .method("get_an_A",&B::get_an_A)</div><div>   .method("get_member_A", &B::get_member_A)</div><div>  ;</div><div>}</div><div><br></div><div><br></div><div><br></div><div>------------------------</div><div><br></div><div>R code:</div><div><br></div><div><div>A_eg <- new(A, 10)</div><div>B_eg <- new(B) </div><div><br></div><div>res <- B_eg$get_member_A()</div><div><br></div><div>rm(res)</div><div># R crashes shortly after running further commands ...</div></div><div># How can this error be prevented?</div></div>