Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector::resize(size_type) requires CopyInsertable?

This question is made while I answer this another question.

N3337 23.3.6.3 "vector capacity" says (it's in 770 page):

void resize(size_type sz);

Effects: If sz <= size(), equivalent to erase(begin() + sz, end());. If size() < sz, appends sz - size() value-initialized elements to the sequence.

Requires: T shall be CopyInsertable into *this.

However, clang++ says it's okay though T is not copyable. And I think it makes sense that resize(size_type) requires only destroyable/moveable/default constructable. It destroys if sz <= size, appends (which uses default constructing, and destroying and moving if the capacity is not enough) if size() < sz.

What is truth? Is it a standard defect? Or is it a mistake of both clang++ and me?

like image 300
ikh Avatar asked Jun 19 '15 11:06

ikh


People also ask

How do you resize a std::vector?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.

How does std::vector resize work?

std::vector::resizeResizes the container to contain count elements. If the current size is greater than count , the container is reduced to its first count elements as if by repeatedly calling pop_back() . If the current size is less than count , additional elements are appended and initialized with copies of value .

Does resizing a vector delete data?

Resizing a vector doesn't destroy the values stored in the vector (except for those beyond the new size when shrinking, of course), however growing a vector beyond its capacity will copy (or, in C++11, move) them to a new place, thus invalidating and iterators, pointers or references to those elements.

Does std::vector assign allocate?

As mentioned above, std::vector is a templated class that represents dynamic arrays. std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.


1 Answers

You are correct. It was a defect in C++11 that was fixed for C++14 by http://cplusplus.github.io/LWG/lwg-defects.html#2033

The current wording says:

Effects: If sz < size(), erases the last size() - sz elements from the sequence. Otherwise, appends sz - size() default-inserted elements to the sequence.

Requires: T shall be MoveInsertable and DefaultInsertable into *this.

The requirement on Destructible is in Table 95 and applies to all operations on all containers, not just resize().

like image 70
Jonathan Wakely Avatar answered Sep 30 '22 19:09

Jonathan Wakely