[Rcpp-devel] Rf_error and Rcpp
Romain Francois
romain at r-enthusiasts.com
Tue May 4 09:35:31 CEST 2010
Hello,
One crucial nugget of information from somewhere in this R-devel thread:
http://article.gmane.org/gmane.comp.lang.r.devel/24284
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
0.8.0)
- use exceptions instead of errors
Something like this:
SEXP foobar( SEXP x_, SEXP y_){
BEGIN_RCPP
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");
END_RCPP
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
--
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- 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