[Rd] Memory allocation in C/C++ vs R?

Andrew Runnalls A.R.Runnalls at kent.ac.uk
Sun May 9 12:37:27 CEST 2010


Dominick,

On 30/04/10 18:40, Dominick Samperi wrote:
> Just to be sure that I understand, are you suggesting that the R-safe way to do
> things is to not use STL, and to not use C++ memory management and
> exception handling? How can you leave a function in an irregular way without
> triggering a seg fault or something like that, in which case there is no chance
> for recovery anyway?

If you had time to try out your work with CXXR, I would be very
interested to hear your experiences.  Picking up on some of the points
already raised in this thread:

1. CXXR's main program is written in C++, so it should deal with C++
initialisation and teardown correctly.  (However, it has been so far
tested only with gcc and the Intel C++ compiler, so there are doubtless
plenty of submerged rocks still to discover.)

2. Within CXXR, all indirect flows of control are handled using C++
exceptions, and it is certainly the intention that user-supplied code
should also be free to use C++ exceptions (subject to the caution that
is always necessary in using C++ exceptions).

3. As regards memory allocation, in addition to the mechanisms available
in standard R, you can of course use standard C++ 'new' and 'delete'.
Also, objects of any C++ class that inherits directly or indirectly from
CXXR::GCNode will be looked after by CXXR's own internal garbage collection.

4. Regarding protection from garbage collection, the mechanisms of
standard R are available.  But for C++ code, the preferred approach is
to use the CXXR::GCRoot<T> and CXXR::GCStackRoot<T> smart pointers.
Basically an object of one of these types behaves like a plain T*
pointer (where T inherits from CXXR::GCNode), but whatever it points to
is protected from garbage collection - for as long as the pointer exists
and points to that object.

Let me know (offline from this list) if I can be of any help.

Andrew Runnalls



More information about the R-devel mailing list