grimme-lab / nlopt-f

Fortran bindings for the NLopt library
Apache License 2.0
28 stars 7 forks source link

Should nlopt_opt be finalized? #11

Closed ivan-pi closed 2 years ago

ivan-pi commented 2 years ago

I'm interested in the rationale behind preserving explicit destruction of the optimization object instance instead of wrapping this within a finalizer.

I can see a few reasons why'd you keep this as the user's responsibility, primarily to avoid dealing with the odd behavior prescribed by the Fortran standard.

awvwgk commented 2 years ago

Actually, the nlopt_opt will destroy the handle automatically using a final procedure:

https://github.com/grimme-lab/nlopt-f/blob/696b0e225fe393f1b77006912f09882c25599c48/src/nlopt_wrap.f90#L146

The destroy procedure is additionally exposed to allow the user to perform this operation manually, since the procedure will check whether the handle is actually associated:

https://github.com/grimme-lab/nlopt-f/blob/696b0e225fe393f1b77006912f09882c25599c48/src/nlopt_wrap.f90#L239-L243

The rationale for having both is that it can be inconvenient to not have a way to manually destroy an object and require it to go out of scope for proper finalization (either by using block or by assignment).

ivan-pi commented 2 years ago

Right, I missed that, sorry. I was only looking at the example in the readme.

I fully agree with your reasoning.

awvwgk commented 2 years ago

Maybe we could update the documentation for this and add a code comment in the example? However, I think that this example might be a bit special, because we are in a program scope which doesn't necessarily call the final procedure on exit but leaves it to the kernel to clean up the used memory after the process terminates. To avoid false positive memory leaks from the C side, manual deconstruction seems like the right thing to do.

ivan-pi commented 2 years ago

By documentation do you mean the Readme? If so, I can I create a PR. Yes, the explicit destruction in the main program scope is a good rule to avoid the false positive when using an application like valgrind.

My question was motivated by my two recent threads:

An artificial example for the auto-finalization in the associate statement, would be a constraint object with a pointer component, that was created using the default structure-constructor directly in the associate statement, instead of declaring at as a (static) target in the main program scope.