[Rcpp-devel] Rf_error and Rcpp

Romain Francois romain at r-enthusiasts.com
Tue May 4 09:35:31 CEST 2010


One crucial nugget of information from somewhere in this R-devel thread: 

When using c++ --- and therefore Rcpp --- it is not safe to call 
Rf_error to stop the c function because error seems to bypass c++ 
unwinding and might leave c++ in an inconsistent state where objects are 
not properly deleted, etc ...

Therefore the recommendation I would promote is to :
- wrap each function by BEGIN_RCPP and END_RCPP (which will arrive with 
- use exceptions instead of errors

Something like this:

SEXP foobar( SEXP x_, SEXP y_){
	std::vector<int> z(3);
	int x = Rcpp::as<int>(x_) ;
	double y = Rcpp::as<double>(y_) ;
	if( x < 0 ) throw std::range_error("no good");
	return Rcpp::wrap( 3 ) ;

This can be facilitated by the new RCPP_* macros:

RCPP_FUNCTION_2( int, foobar, int x, double y){
	std::vector<int> z(3) ;
	if( x < 0 ) throw std::range_error("no good");
	return 3 ;

because this exit the flow through c++ exceptions, this will properly 
unwind the stack and therefore deal with z. From what I understand of 
Simon's emails in R-devel, using Rf_error here instead of throw would 
not delete z.

I'm sending this here because I seem to recall people mixing C++ and 
error (no documentation says one should not anyway) but I don't remember 
where (maybe minqa or lme4a).


Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
|- http://bit.ly/9aKDM9 : embed images in Rd documents
|- http://tr.im/OIXN : raster images and RImageJ
|- http://tr.im/OcQe : Rcpp 0.7.7

More information about the Rcpp-devel mailing list