Reputation: 941
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?
Upvotes: 6
Views: 247
Reputation: 234695
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.
Upvotes: 7
Reputation: 16876
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.
Upvotes: 9