Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Take the following code:

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

a.reserve(65536); // no reallocation
b.reserve(65536);

Is capacity copied? Will there be a reallocation on the last line? Does the standard say anything about this or is it silent?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
201 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is capacity copied?

In practice, no. I tested it online in Clang and GCC as well as MSVC and none of them copy the capacity.

Will there be a reallocation on the last line?

If the capacity is less than the argument to reserve (i.e. it doesn't get copied) then yes.

Does the standard say anything about this or is it silent?

No definitions for the copy constructor are provided in vector.cons. Instead we have to look at the container.requirements

X denotes a container class containing objects of type T, a and b denote values of type X, u denotes an identifier, r denotes a non-const value of type X, and rv denotes a non-const rvalue of type X.

X u(a)

X u = a;

Requires: T is CopyInsertable into X (see below).

post: u == a

Now what does it mean for two containers to be equal?

a == b

== is an equivalence relation. equal(a.begin(), a.end(), b.begin(), b.end())

In other words, since it doesn't require capacity to be equal in the comparison, then there's no reason to copy the capacity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...