Is capacity copied in a vector?

前端 未结 5 1835
野的像风
野的像风 2020-12-10 00:44

Take the following code:

std::vector a;
a.reserve(65536);
std::vector b(a);  //NOTE: b is constructed from a

a.reserve(65536); // no r         


        
5条回答
  •  清歌不尽
    2020-12-10 00:55

    Standard says nothing about preserving capacity when you call copy constructor. So you have no any guarantees about it.

    But you can do the following trick, which swap a's and b's state, if you need preserving capacity in the copy only:

     std::vector a;
     a.reserve(65536);
     std::vector b(a);
     b.swap(a); // now b has a's state
     assert(b.capacity() == 65536); 
    

提交回复
热议问题