[R] error() and C++ destructors

Lennart.Borgman@astrazeneca.com Lennart.Borgman at astrazeneca.com
Tue Mar 9 13:34:30 CET 2004


I am sending this reply on behalf of Erik (who is not a member of this
list).

- Lennart


-----Original Message-----
From: Källen, Erik 
Sent: 9 mars 2004 11:37
To: Borgman, Lennart
Subject: RE: [R] error() and C++ destructors


I would do something like:

class error_exception {
public:
	error_exception(const string &str) : msg(str) {}
	string msg;
};

void my_error(const string &str) {
	throw error_exception(str);
}

int real_my_method(int a, char *b) {
	/*
	some code...
	*/
	return 0;
}

// this is the public method:
int my_method(int a, char *b) {
	try {
		return real_my_method(a, b);
	}
	catch (error_exception &e) {
		error(e.msg);
	}
}

You could probably even create a macro like:
#define R_METHOD_IMPL(rettype, name, paramlist) \
rettype real_##name paramlist; \
rettype name paramlist { \
	try { \
		return real_##name paramlist; \
	} \
	catch (error_exception &e) { \
		error(e.msg); \
	} \
} \
rettype real_##name paramlist


You would use this macro like:
R_METHOD_IMPL(int, my_method, (int a, char *b)) {
	// source code here
}

I think it would work, but I'm not sure (untested).


/Erik Källén


-----Original Message-----
From: Vadim Ogranovich [mailto:vograno at evafunds.com]
Sent: 2 mars 2004 22:00
To: R Help List
Subject: [R] error() and C++ destructors


Hi,
 
I am writing C++ functions that are to be called via .Call() interface.
I'd been using error() (from R.h) to return to R if there is an error,
but then I realized that this might be not safe as supposedly error()
doesn't throw an exception and therefore some destructors do not get
called and some memory may leak. Here is a simple example
 
extern "C" void foo() {
    string str = "hello";
    error("message");
}
 
The memory allocated for str is leaked.
 
Did anyone think about this and find a way to work around the problem?
 
Thanks,
Vadim

	[[alternative HTML version deleted]]

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list