Free memory allocated on the C++ side by MakeADFun.

FreeADFun(obj)

Arguments

obj

Object returned by MakeADFun

Details

An object returned by MakeADFun contains pointers to structures allocated on the C++ side. These are managed by R's garbage collector which for the most cases is sufficient. However, because the garbage collector is unaware of the C++ object sizes, it may fail to release memory to the system as frequently as necessary. In such cases one can manually call FreeADFun(obj) to release the resources.

Note

This function is normally not needed.

Memory management

Memory allocated on the C++ side by MakeADFun is represented by external pointers. Each such pointer has an associated 'finalizer' (see reg.finalizer) that deallocates the external pointer when gc() decides the pointer is no longer needed. Deallocated pointers are recognized on the R side as external null pointers <pointer: (nil)>. This is important as it provides a way to prevent the finalizers from freeing pointers that have already been deallocated even if the deallocation C-code has been unloaded. The user DLL maintains a list of all external pointers on the C side. Three events can reduce the list:

  • Garbage collection of an external pointer that is no longer needed (triggers corresponding finalizer).

  • Explicit deallocation of external pointers using FreeADFun() (corresponding finalizers are untriggered but harmless).

  • Unload/reload of the user's DLL deallocates all external pointers (corresponding finalizers are untriggered but harmless).

Examples

runExample("simple", thisR = TRUE)          ## Create 'obj'
#> Building example simple 
#> Note: Using Makevars in /data/user-homes/elizabethb/.R/Makevars 
#> using C++ compiler: ‘g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0’
#> Build time 46.115 seconds
#> 
#> Running example simple 
#> 
#> > require(TMB)
#> 
#> > dyn.load(dynlib("simple"))
#> 
#> > set.seed(123)
#> 
#> > y <- rep(1900:2010, each = 2)
#> 
#> > year <- factor(y)
#> 
#> > quarter <- factor(rep(1:4, length.out = length(year)))
#> 
#> > period <- factor((y > mean(y)) + 1)
#> 
#> > B <- model.matrix(~year + quarter - 1)
#> 
#> > A <- model.matrix(~period - 1)
#> 
#> > B <- as(B, "TsparseMatrix")
#> 
#> > A <- as(A, "TsparseMatrix")
#> 
#> > u <- rnorm(ncol(B))
#> 
#> > beta <- rnorm(ncol(A)) * 100
#> 
#> > eps <- rnorm(nrow(B), sd = 1)
#> 
#> > x <- as.numeric(A %*% beta + B %*% u + eps)
#> 
#> > obj <- MakeADFun(data = list(x = x, B = B, A = A), 
#> +     parameters = list(u = u * 0, beta = beta * 0, logsdu = 1, 
#> +         logsd0 = 1), random = .... [TRUNCATED] 
#> 
#> > opt <- nlminb(obj$par, obj$fn, obj$gr)
FreeADFun(obj)                              ## Free external pointers
#> NULL
obj$fn()                                    ## Re-allocate external pointers
#> [1] 375.0672
#> attr(,"logarithm")
#> [1] TRUE