[Rcpp-devel] Life-cycle of Rcpp::XPtr
Hi Ralf,
On Sat, 23 Sept 2023 at 14:56, Dirk Eddelbuettel <edd at debian.org> wrote:
Hi Ralf, On 23 September 2023 at 08:28, Ralf Stubner wrote: | I have a question concerning the file-cycle of Rcpp::XPtr: Consider a | XPtr with the default delete finalizer wrapping some pointer. If I use | the copy constructor to create another XPtr, this is pointing at the | same underlying object as expected. What happens if one of these | pointers goes out of scope and is at some point garbage collected? Is | the underlying object deleted leaving the other XPtr with a broken | pointer? Or is the object protected by the existence of the other | pointer? From my experiments I have the impression that the latter is | the case, which would be the desired behaviour. But it would be nice | if one could be sure.
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
I?aki ?car Assistant Professor of Statistics Director of the Master in Computational Social Science Department of Statistics | Big Data Institute Universidad Carlos III de Madrid Av. de la Universidad 30, 28911 Legan?s, Spain Office: 7.3.J25, Tel: +34 916248804