doubt about the behavior of std :: swap

0

Note:

Reading the answers to this question: How does std :: move work? In the case of std :: move does not move, I generated this doubt, in case it is not a problem in a code that I need to solve, but rather in question the behavior of std :: move, but, of std :: swap. To imagine a use case for the code below, one might think that v_note is a vector of tabs, and that the class in which it belongs manipulates the insertion, removal, and get (get) of the tabs, note_counter is incremented in function insertChild always pointing to the v_note index that has not yet been initialized, and is decremented by the remove function, and Widget * will be a any widget that will be nested the tab, for example, a text field or an image area. p>

Doubt:

Regarding the remove function, std :: swap performs what I'm hoping for ?, I say the remove function does the following:

  • Sort the vector, using std :: swap, changing the pointers nulls by non-nulls, thus, by ordering nonzero pointers in the start of the vector.

  • Redefine the ids of each Widget.

  • The code runs normally, the debug shows that the pointers that were 'swapped' by std :: swap are actually null, and my doubt goes right there, with this sort of sorting technique I mentioned, it generates or can I generate a dangling pointer?

    Code:

    void attach( Widget* parent ){ ... }
    void insertChild( Widget* child ){ ... }
    
    void remove( const WidgetID& index )
    {
        //analizo se index está dentro do range de abas inicializadas
        if( index >= 0 && index < note_counter )
        {
           //libero os recursos do widget aninhado a minha aba
            v_note[ index ]->Destroy(); 
            delete v_note[ index ];
            v_note[ index ] = nullptr;
    
            //Ordenação simples    
            if( note_counter > 1 )
            {
                for( size_t i = 0; i < note_counter - 1; i++ )
                {
                    for( size_t j = 1; j < note_counter; j++ )
                    {
                        if( v_note[ i ] == nullptr && v_note[ j ] != nullptr )
                        {
                            //Dúvida
                            std::swap( v_note[ i ], v_note[ j ] );
                        }
                    }
               }
           }
           //decrementa o contador e reordena as ID's 
           if( note_counter > 0 ){ note_counter-= 1; }
           for( size_t i = 0; i < m_counter; i++ )
           {
               if( v_note[ i ] != nullptr ){ v_note[ i ]->SetID( i ); }  
       }
    }
    
        
    asked by anonymous 22.01.2018 / 21:40

    0 answers