C++ vector::clear

后端 未结 6 1092
死守一世寂寞
死守一世寂寞 2020-12-09 09:03
vector  decoy;

void clear_decoy() {  

    decoy.clear();   

    vector (decoy).swap(decoy);  
}

In the above method

6条回答
  •  忘掉有多难
    2020-12-09 09:27

    That code is a failed attempt to use a common trick to ensure the memory allocated by the vector is freed. It may or may not actually do that, depending on whether or not the vector's copy constructor allocates memory to match the other vector's size, or its capacity.

    To reliably free the memory, use the following:

    void clear_decoy() {  
        vector().swap(decoy);  
    }
    

    This creates a temporary empty vector (with little or no memory allocated), swaps this with decoy so that the memory is now owned by the temporary, then destroys the temporary, freeing the memory.

提交回复
热议问题