ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.06k stars 493 forks source link

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

Open ImAlien opened 1 year ago

ImAlien commented 1 year ago

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?

congard commented 9 months ago

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