Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector capacity shows 0 even though it is reserved

Tags:

c++

vector

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?

like image 563
sungjun cho Avatar asked Jun 03 '19 11:06

sungjun cho


People also ask

Can vector have a size of zero?

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.

Can a vector have size 0 C++?

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.

How do you set the capacity of a vector?

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.

How do you reserve a space in vector?

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.


2 Answers

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.

like image 117
Blaze Avatar answered Nov 15 '22 05:11

Blaze


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.

like image 24
Bathsheba Avatar answered Nov 15 '22 07:11

Bathsheba