sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

Can I free the c++ memory manually when I don't use the c++ object?

Open ImAlien opened this issue 1 year ago • 1 comments

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?

ImAlien avatar Jun 21 '23 03:06 ImAlien

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

congard avatar Sep 24 '23 19:09 congard