Is `R_ClearExternalPtr()` needed to finalize an external pointer object in R?

Viewed 20

While reading Writing R Extensions, Section 5.13 External pointers and weak references we see an example of a finalizer using R_ClearExternalPtr() albeit the comment next to it saying not really needed:

(...) The finalizer code is simply

static void chanFinalizer(SEXP ptr)
{
if(!R_ExternalPtrAddr(ptr)) return;
inRODBCClose(R_ExternalPtrAddr(ptr));
R_ClearExternalPtr(ptr); /* not really needed */
}

In the post Storing C objects in R by @Martin-Morgan he provides two finalizer examples, where he does include a call to R_ClearExternalPtr() in the first case but not in the second:

First example:

static void
_finalizer(SEXP ext)
{
    if (NULL == R_ExternalPtrAddr(ext))
        return;
    Rprintf("finalizing\n");
    char *ptr = (char *) R_ExternalPtrAddr(ext);
    Free(ptr);
    R_ClearExternalPtr(ext);
}

Second example:

static void
_finalizer(SEXP ext)
{
    struct Foo *ptr = (struct Foo*) R_ExternalPtrAddr(ext);
    Free(ptr);
}

Can someone help clarify the comment not really needed, and whether I should call R_ClearExternalPtr() at the end of the finalizer.

0 Answers
Related