Reputation: 7927
I have an object A
, that I want to wrap with a list of objects (pointers to objects) of type B
, that A
should process.
The problem is, that some of B
objects can be deleted and A
doesn't know about it. I know I can handle it with exceptions, but I would rather to avoid it.
Full problem: I'm writing C++ SFML project, I want to wrap a sf::RenderWindow
with a vector of sf::Drawable *
pointers to objects, that window should draw. And problem is the same. Some of sf::Drawable
objects may be already deleted, but sf::RenderWindow
tries to use it.
I can possibly cancel the idea of wrapping, but if there a good design solution, it would be great.
Upvotes: 2
Views: 73
Reputation: 48635
You can use a std::unique_ptr which will return true
or false
in an if()
statement depending if it has been deleted or not:
// use a std::unique_ptr that will record if its target has been deleted
std::vector<std::unique_ptr<sf::Drawable>> drawables;
// deleting an element
for(auto& drawable: drawables)
{
if(needs_to_be_deleted(drawable.get()))
drawable.reset(); // deletes object
}
// process elements
for(auto& drawable: drawables)
{
if(drawable) // returns false if element is deleted
{
// pass by reference or pointer (using get())
do_something_with_drawable(drawable.get());
}
}
Upvotes: 2
Reputation: 13085
You have to ensure memory is not reused, as it will result in undefined behavior if the object is no longer live when you use it.
Create a map for the live objects, and only use value, if it is still in the map
Upvotes: 0