sol2
sol2 copied to clipboard
Can I free the c++ memory manually when I don't use the c++ object?
like this, in my lua sctipt
for i = 1, 1000 do
local obj = MyObject.new()
end
I want to execute the deconstructor of MyObject every loop to free the memory, is this viable?
In the example you provided, all created objects will be destroyed by the garbage collector, e.g.:
sol::state state;
auto foo = state.new_usertype<Foo>("Foo");
state.script("for i = 1, 2 do local _ = Foo.new() end");
Output:
ctor
ctor
dtor
dtor
You can run garbage collector manually by using sol::state::collect_gc
, e.g.:
sol::state state;
auto foo = state.new_usertype<Foo>("Foo");
state.script("for i = 1, 2 do local _ = Foo.new() end");
std::cout << "Before gc\n";
state.collect_gc();
std::cout << "After gc\n";
Output:
ctor
ctor
Before gc
dtor
dtor
After gc
If you want to manage memory manually, you can use for example factories: https://sol2.readthedocs.io/en/latest/api/usertype.html#new-usertype-set-options