Question

I have a class and a vector of pointers to instances of the class in c++. I want to be able to query both kinds of objects in R using Rcpp. However the data member of my class seems to get corrupted for no reason. Since I'm not able to consistently reproduce the error I'm guessing it has something to do with memory being released that shouldn't have.

I have also tried designing my own container class, but it suffered from the same problem.

Below I have tried to make a minimal example

#include <Rcpp.h>
using namespace Rcpp;

class Element{
  private:
    int x;
  public:
    Element() : x(0){};
    Element(int x_) : x(x_){};
    void display() {Rcpp::Rcout << x << std::endl;}
};

typedef std::vector<Element*> Container;

RCPP_EXPOSED_CLASS(Element)

//R Side

RCPP_MODULE(mod){
  class_<Element>("Element")
    .constructor<int>()
    .method("display", & Element::display);


  class_<Container>("Container")
    .constructor()
    .constructor<int>()
    .method("push_back", & Container::push_back)
    .const_method("at", & Container::at )
    .const_method("size", & Container::size )
  ;
}

/*** R
container <- new(Container)

container$push_back( new(Element, 5))
container$push_back( new(Element, 6))

container$size()

myElements <- list()
myElements[[1]] <- container$at(0)
myElements[[1]]$display()
*/

I had to query a few more times in R to get the error below is my output

> Rcpp::sourceCpp('src/Element.cpp')
> container <- new(Container)
> container$push_back( new(Element, 5))
> container$push_back( new(Element, 6))
> container$size()
[1] 2
> myElements <- list()
> myElements[[1]] <- container$at(0)
> myElements[[1]]$display()
5
> myElements[[2]] <- container$at(1)
> myElements[[1]]$display()
5
> myElements[[2]]$display()
6
> myElements[[1]]$display()
61412608

EDIT: I was able to compile this in a windows environment after adding two functions

Element* container_at(std::vector<Element*> * vec, int i){
  return vec->at(i);
}

int container_size(std::vector<Element*> * vec){
  return vec->size();
}

and replacing

.const_method("at", & Container::at )
.const_method("size", & Container::size )

with

.method("at", & container_at )
.method("size", & container_size )
Was it helpful?

Solution

That is a bug. Can you log it here: https://github.com/RcppCore/Rcpp/issues?state=open

I have a good idea of what it might be and how it can be fixed, but I might not have time for a few days.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top