Reputation: 2796
I've got a mixed C [cblas] / C++ [library code] library (developed by someone else) that I have wrapped in Rcpp.
Many methods have code like the one below:
void myclass::calculate() {
double* dataSums = (double*) calloc(N, sizeof(double));
if(dataSums == NULL) { printf("Memory allocation failed!\n"); exit(1); }
// do some calculations ...
cblas_dgemm(...);
free(dataSums); dataSums = NULL;
}
Of course, the exit(1)
is a problem here: when called from R, it shuts R down as well, which is what I don't want.
What is the best way to make sure that:
exit
calls with exceptions?)std::vector
s?)Upvotes: 1
Views: 753
Reputation: 368409
I would suggest something like
if (dataSums == NULL) Rcpp::stop("Memory allocation failed!\n");
You have the corresponding (C++) layer of try / catch
wrapped around your code anyway
if you use Rcpp attributes, or inline, or when you do it by hand following the examples we have provided over the years. And given the C++ exception layer, you can just use it.
If your code layer needs extra cleanup, you may add that layer there. But C++ data structures will be unwound properly.
Upvotes: 6