nodejs / node-addon-api

Module for using Node-API from C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Returning a Reference to a Class Member from a Class in node-addon-api Description

vaguue opened this issue · comments

Dear node-addon-api team,

First of all, I would like to extend my gratitude to you all for your work on this project. It has been incredibly beneficial for my work.

Currently, I am developing a project using node-addon-api and have encountered a situation that I would appreciate your input on. Consider the following C++ code:

struct  A {
  int a = 0;
};

struct B {
  std::vector<A> a;
  B() : a(20) {};
  A& someMethod(int i) {
    return a[i];
  }
};

I have the ObjectWrap versions for both classes. On the JavaScript side, if we execute const a = new B().someMethod(5);, the instance of B will be garbage collected post execution, potentially resulting in the loss of a. Further, if any elements of the vector are garbage collected, it could lead to undefined behavior.

I am seeking advice on how to ensure that the return value of someMethod gets garbage collected only if both the parent (B) and the child (A) can be safely freed. Is there a way to implement this in node-addon-api? Any advice or suggestions would be greatly appreciated.

Thank you in advance for your time and assistance.

It sounds like you might need to use References - https://github.com/nodejs/node-addon-api/blob/main/doc/reference.md

There has not been a follow up in over a month so I'm going to close this. Please let us know if that was not the right thing to do.