emscripten-core / emscripten-core/emscripten

Embind: no way to implement shared_ptr factory in JS without memory leak?

Open
#19,200 5 comments 0 reactions 0 assignees View on GitHub
embind
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

Given simple factory class like:

```
struct SomeClass { … };

struct SomeClassFactory {
virtual std::shared_ptr makeSomeClass() = 0;
};
```

I'm able to successfully export `SomeClass` and `SomeClassFactory` so they are visible and overridable from JS. Everything is also kept as shared_ptr's.

The problem I have is I can't find a way to actually implement `SomeClassFactory::makeSomeClass()` method in JS without leaking created `shared_ptr`. Simplest example of such implementation:

```
var SomeClassFactoryJS = Module.SomeClassFactory.extend("SomeClassFactory", {
makeSomeClass: function() {
return new Module.SomeClass();
},
});
```

Basically I create JS object wrapping `shared_ptr` and return it from factory method – so I cannot call `delete()` on it (I tried doing that before returning and it failed). The result of this is destructor of `SomeClass` is never called, because it's "retained" by original JS object wrapping it.

Is is possible to pass `shared_ptr` in such way without falling back to calling `delete()` asynchronously before returning? Am I missing something?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.