mercredi 6 février 2019

Raw pointer vs smart-pointer in C++11 [duplicate]

This question already has an answer here:

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?

Aucun commentaire:

Enregistrer un commentaire