Does a vector assignment invalidate the `reserve`?

前端 未结 3 1694
天命终不由人
天命终不由人 2021-02-01 15:03

Suppose I write

std::vector littleVector(1);
std::vector bigVector;

bigVector.reserve(100);
bigVector = littleVector;

Does t

3条回答
  •  你的背包
    2021-02-01 15:18

    The only requirement on operator= for standard containers is that afterwards, src == dst, as specified in Table 96 (in 23.2, General Container Requirements). Furthermore, the same table specifies the meaning of operator ==:

    distance(lhs.begin(), lhs.end()) == distance(rhs.begin(), rhs.end()) // same size
      && equal(lhs.begin(), lhs.end(), rhs.begin()) // element-wise equivalent
    

    Note that this doesn't include capacity in any way. Nor does any other part of the standard mention capacity beyond the general invariant that capacity() >= size(). The value of capacity after assignment is therefore unspecified, and the container is free to implement assignment whichever way it wants, as long as allocator requirements are kept.


    In general, you will find that implementations behave such that

    • if the allocators compare equal and dst has sufficient capacity, it will retain its old storage,
    • otherwise it will allocate just enough storage for the new elements, and
    • in no case will care what the capacity of src is.

    Of course, move assignment is a different story. Since it is generally implemented by stealing the source storage, the capacity will be taken as well.

提交回复
热议问题