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

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

c++ - Is capacity copied in a vector?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...