Example Object Wrapping code never calls destructor

  • Version: v9.11.1
  • Platform: Windows 10 Enterprise 64-bit
  • Subsystem: documentation

The documentation for Wrapping C++ Objects has an example that creates a class called MyObject which derives from node::ObjectWrap.

It would be very helpful if the documentation described the mechanism by which the object will be deleted (how/when) and provided an example of how to get the destructor to actually be invoked in practice, since it will only get deleted when the garbage collector runs. As I understand it (as I am able to demonstrate by running the example), the destructor will not get called. The example suggests that one is intended to run the following code, which will not induce a garbage collection:

// test.js
const addon = require('./build/Release/addon');

const obj = new addon.MyObject(10);
console.log(obj.plusOne());
// Prints: 11
console.log(obj.plusOne());
// Prints: 12
console.log(obj.plusOne());
// Prints: 13

It would be much better if there were an example that shows how to force a garbage collection that causes the wrapped object to get properly destroyed so that developers of addons can ensure that C++ resources are not leaked.

As I see it, this is only half an example because it only demonstrates creating objects, not destroying them. They are not demonstrated to get destroyed using this example code. I think this is a shortcoming of the documentation.