<div dir="ltr"><div><div><div><div>Hello Everybody,<br><br></div>I am trying to create tree data structure using C++ and Rcpp and use it from R.<br></div>I want to incrementally build the tree by merging a tree with other tress. So, I created a class for the tree and a class for the nodes in the tree. The tree class has two constructors, the first one simply creates a tree with a single leaf. The second constructor takes two external pointers pointing to two trees and creates a new tree be joining the two trees with a new node. In the R side I create a tree (tree1) and repeatedly add another tree (tree2) in the first tree. Here is the C++ and R code.<br>

<br><br>#include <Rcpp.h><br>class treeNode<br>{<br>public:<br>  treeNode* left;<br>    treeNode* right;<br>};<br><br>class tree<br>{<br>private:<br>   treeNode* root;<br>public:<br>    tree();<br>    tree(SEXP, SEXP);<br>

    SEXP getPointer();<br>    void addTree(SEXP ptr2);<br>};<br><br><br>tree::tree()<br>{<br>  root = new treeNode;<br>  root->left = NULL;<br>  root->right = NULL;<br>}<br><br>// merge two tree and create a new tree<br>

tree::tree(SEXP ptr1, SEXP ptr2)<br>{<br>  Rcpp::XPtr<tree> tree1(ptr1);<br>  Rcpp::XPtr<tree> tree2(ptr2);<br><br>  root = new treeNode;<br>  root->left = tree1->root;<br>  root->right = tree2->root;<br>

}<br><br>SEXP tree::getPointer()<br>{<br>  Rcpp::XPtr<tree> ptr(this, true);<br>  return ptr;<br>}<br><br>RCPP_MODULE(yada){<br>  using namespace Rcpp ;<br>    class_<tree>("tree")<br>            .constructor()<br>

            .constructor<SEXP, SEXP>("create a new tree by merging two existing trees")<br>            .method("getPointer", &tree::getPointer, "getPointer")<br>            ;<br>}<br>

<br><br></div>I created a package called test and then call the functions from  R side <br></div>The R code looks like the following:<br><div><br>require(test)<br><br>t1 = new(tree)<br>t2 = new(tree)<br>t1 = new(tree, t1$getPointer(), t2$getPointer())<br>

gc()<br><br>t2 = new(tree)<br>t1 = new(tree, t1$getPointer(), t2$getPointer())<br>gc()<br><br><br></div><div>After second garbage collector call I am getting segmentation fault . Can you please explain the right way to program this scenario? In particular, when a C++ object is still used by another object through pointer how can I prevent R garbage collector removing the object ?<br>

<br><br></div><div>Thanks<br><br></div><div>Ariful Azad<br><br></div><div><div><br></div></div></div>