Problem
I have a template container MyContainer<std::unique_ptr<Foo>> which has a std::deque<T> and a std::vector<T> member.
Inside method, send_to_purgatory_if( predicate ), I would like to look at all items in m_taskdq and move items from m_taskdq to m_purgatory, if the predicate evaluates to true.
Issues
I have two issues that I'm struggling with:
- my iterator
itgets trashed if I remove items from m_taskdq from inside the loop - I am worried about the state of the
std::unique_ptr<>if I do the move in two steps (problem lines 1 and 2 - by line 2, I think thestd::unique_ptr<>pointed to byitis undefined?)
How should I fix this code?
template <typename T>
class MyContainer
{
typedef std::function<bool(T&)> PREDICATE;
void send_to_purgatory_if( PREDICATE p )
{
// bad code -------------------------------------
for( auto it=m_taskdq.begin(); it!=m_taskdq.end(); ++it )
{
if ( p( *it ) )
{
m_purgatory.emplace_back( move( *it )); // problem line 1
m_taskdq.erase( it ); // problem line 2
}
}
// end bad code ---------------------------------
}
std::deque< T > m_taskdq;
std::vector< T > m_purgatory;
};