Skip to content
Prev 10894 / 10988 Next

[Rcpp-devel] Life-cycle of Rcpp::XPtr

Hi Ralf,
On Sat, 23 Sept 2023 at 14:56, Dirk Eddelbuettel <edd at debian.org> wrote:
The answer is yes, XPtr works as a shared_ptr, so you can be sure that
the object will be protected until the last reference to it is
deleted. A quick check:

#include <Rcpp.h>
using namespace Rcpp;

class Test {
public:
  Test()  { Rcout << this << " created" << std::endl; }
  ~Test() { Rcout << this << " deleted" << std::endl; }
};

// [[Rcpp::export]]
SEXP test_new() {
  return XPtr<Test>(new Test());
}

// [[Rcpp::export]]
SEXP test_copy(SEXP x_) {
  XPtr<Test> x(x_);
  return x;
}

/*** R
x <- test_new()
#> 0x55a93e3845d0 created
y <- test_copy(x)
rm(x); invisible(gc())
rm(y); invisible(gc())
#> 0x55a93e3845d0 deleted
*/

Best,
I?aki