C++ vector::clear

后端 未结 6 1073
死守一世寂寞
死守一世寂寞 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:15

    It creates a new vector of Weight objects (which will be empty) and swaps it with decoy.

    The reason for this is that by default, std::vector::clear often doesn't actually reduce the storage used by a vector, it merely destroys all the objects contained there. This way, the vector has room to store more objects without reallocation in the future.

    Sometimes, however, you want to trim the capacity in the vector. Swapping with a newly created vector (which lives until the end of it's line, and is therefore destroyed there) frees all the memory allocated by the vector.

提交回复
热议问题