I have a class that has a vector as one of member variables. Within the constructor, the vector capacity is reserved (class VecUser uses 'Test' object):
class Test {
public:
Test(uint32_t size) {
this->v.reserve(size);
std::cout << v.capacity() << std::endl; // this prints 'size'
}
vector<uint32_t>& getV() { return v; }
private:
vector<uint32_t> v;
};
class VecUser {
public:
VecUser() {}
private:
void func() {
Test* test = new Test(32); // This prints '32'
vector<uint32_t> v = test->getV();
std::cout << v.capacity() << std::endl; // This prints '0'
}
};
I think that the cout
in the func()
function has to print '32', not '0'.
But, after running it, it prints 0.
Why the reserved vector shows its capacity is 0?
We define a vector as an object with a length and a direction. However, there is one important exception to vectors having a direction: the zero vector, i.e., the unique vector having zero length. With no length, the zero vector is not pointing in any particular direction, so it has an undefined direction.
This question already has answers here: The size() for vectors in C++ standard library returns zero The size() is supposed to return the current number of elements.
The theoretical limit on the size of a vector is given by member max_size. The capacity of a vector can be explicitly altered by calling member vector::reserve.
C++ Vector Library - reserve() Function The C++ function std::vector::reserve() requests to reserve vector capacity be at least enough to contain n elements. Reallocation happens if there is need of more space.
This here
vector<uint32_t> v = test->getV();
Makes a copy. v
isn't actually a reference, so even though you return one, it has to make a copy anyway. Because it is a copy, it doesn't need that same amount of reserved space. If you actually get the reference instead like this:
vector<uint32_t> &v = test->getV();
The output is 32
both times.
The copy-initialized v
following vector<uint32_t> v = test->getV();
is a value copy of test->getV()
.
The C++ standard does not require the copying of the source vector's capacity following copy initialization, so the capacity of v
is allowed to be any value subject to it being greater than or equal to the number of elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With