Skip to content
Prev 2190 / 10988 Next

[Rcpp-devel] Const Reference Arguments for class methods in Rcpp-Module

Hi Dirk,
Thank you for your reply. Is there a specific bug tracking site for 
Rcpp? Meanwhile, I will post an example here. The following C++ code 
defines two classes, A and B. Their constructors take a vector and print 
it to the terminal. 'A' works with a const reference, 'B' takes the 
argument by value.

--------------
C++ Code
--------------
#include <Rcpp.h>
using namespace Rcpp;

class A {
   public:
     A(const Rcpp::NumericVector& v) {
       for (int i=0; i<v.size(); ++i) {
	std::cout << v[i] << std::endl;
       }
     }

     void foo(const Rcpp::NumericVector& v) {
       for (int i=0; i<v.size(); ++i) {
	std::cout << v[i] << std::endl;
       }
     }
};

class B {
   public:
     B(Rcpp::NumericVector v) {
       for (int i=0; i<v.size(); ++i) {
	std::cout << v[i] << std::endl;
       }
     }
};

RCPP_MODULE(TestMod) {
   class_<A>( "A" )
     .constructor<const Rcpp::NumericVector&>("Constructor A.")
     .method("foo", &A::foo, "Print a vector.")
   ;

   class_<B>( "B" )
     .constructor<Rcpp::NumericVector>("Constructor B.")
   ;
}
------------

Loading the library and using the module in R yields the following:

------------
R session
------------
 > a <- new(A, c(1,2,3))
4.68671e-318
 > a$foo(c(1,2,3))
1
2
3
 > b <- new(B, c(1,2,3))
1
2
3
-------------

Note that for the constructor of 'A', not even the size of the vector is 
interpreted correctly. This may randomly lead to segfaults. The methods 
A::foo() and B::B(), however, work as expected.
This is a very interesting topic. In fact, most of my code relies on STL 
containers directly. The class exposed to R is actually a facade for a 
pure virtual C++ class. Only within this facade, I use 
Rcpp::NumericVector. Many of the functions in the remaining code take 
iterator ranges. Thus, I can operate on Rcpp vectors or STL vectors 
without copying.

Using const references in the exposed classes is not essential for my 
program. I did it out of a habit. I am worried about the fact that it 
compiles without error and yields somewhat undefined behaviour, though.


Best regards,
Peter