Tr1::bad_weak_ptr upon accessing an object that has been garbage-collected

I mentioned this somewhere a few years ago but it wasn’t really a proper bug report, more of a joke, but I guess I’ll just report it.

In the following code,

local model = Instance.new("Model")
Instance.new("Model", model)
model.DescendantRemoving:connect(function(child)
	print(child.Parent)
end)

The line with print(child.Parent) causes an error message saying tr1::bad_weak_ptr to appear.

I was thinking it might be nicer if instead of just tr1::bad_weak_ptr, it showed a proper error message like “Attempt to access an object that has been garbage-collected”.

Assuming you use std::exception.what(), it could probably easily be implemented like this (std::runtime_error is defined in <stdexcept>):

try {
    try {
        ...
    } catch (const tr1::bad_weak_ptr &ex) {
        throw std::runtime_error("Attempt to access an object that has been garbage-collected");
    }
} catch (const std::exception &ex) {
    // code where you originally used and handled ex.what()
}

Note that this bug has been reported in the past by someone who did not understand the cause, who was rather confused by it, thus proving that it would be useful to make the error message more descriptive:

Thank you for your time.

1 Like

I’m more surprised that it fires DescendantRemoving

Actually, if you put it like that, I guess making it not fire DescendantRemoving might be an even better solution.
Either that, or the deletion/collection of the parent should be postponed until after all the children have been collected and destroyed.