[Rcpp-devel] Rcpp-devel] What is the best practice to expose a C structure from 3rd party library into R?

Dirk Eddelbuettel edd at debian.org
Tue Jul 23 19:13:35 CEST 2013


On 23 July 2013 at 11:50, Steve Jaffe wrote:
| on: Tue, 23 Jul 2013 11:37:25 -0500
| Dirk Eddelbuettel <edd at debian.org> wrote:
| 
| > | A singleton does make things easier. However, I still want to know how to
| > | expose C structure with provided `free`-like function because sometimes we
| > | cannot use singleton.
| > 
| > Manage your objects carefully, and don't call free() on NULL pointers.
| 
| According to the C standard, it is safe to call free on a null pointer. Similarly, according to the C++ standard, it is safe to call 'delete' on a null pointer.
| 
| Thus there is no need ever to test a pointer for null before free-ing/delete-ing. 
| 
| However, it *is* good practice to assign null to a pointer *after* free-ing/delete-ing, since that ensures that any subsequent calls to free/delete will be safe.
| 
| What is dangerous is calling free/delete twice on the same *non-null* pointer.

Thanks for the correction.  I obviously shouldn't have mixed malloc/free with
new/delete in the discussion.

I rarely need to write code that uses new/delete these days as I much prefer
to rely on STL containers -- a programming style advocated by just about
every modern C++ text (incl Stroustrup, 2013, 4th ed).  And by just about all
Rcpp examples we provide.   

Dirk

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com


More information about the Rcpp-devel mailing list