I'm trying to understand how can I substitute raw pointers on my C++ software with smart-pointers.
I have the following code:
class Foo { private: std::vector<Bar *> m_member; }; Now in some function I populate that vector with:
m_member.push_back( new Bar() ); and when my program finishes I delete the memory with:
for( std::vector<Bar *>::iterator it = m_member.begin(); it < m_member.end(); ++it ) { delete (*it); (*it) = NULL; } Now all this is good.
The problem is as I see it comes from the fact that at one point of time I may need to delete one of the member from the vector (this member is user-specified).
Now this is easy:
for(...) { if( (*it)->GetFieldFromBar() == <user_specified_condition> ) { delete (*it); (*it) = NULL; } } But how do I re-write it with the smart pointers? Is it even possible?
std::vector<Bar *> m_member;tostd::vector<std::unique_ptr<Bar>> m_member;. Then if you need to delete an element you justeraseit.std::vector<Bar >not suffice?