1

I understand how std::vector::reserve() works with vectors of primitive types:

vector<int> vec;
vec.reserve(100);

Say you created an empty vector of objects:

class A {
    public:
    string name;
}

vector<A> vec;
vec.reserve(100);

How does it know how much memory to reserve? Not only that, but what if class A had a container inside of it as well? Then it would be impossible to reserve the correct amount of memory right?

kawgit
  • 55
  • 5
  • 1
    `sizeof(A)` is a fixed value which doesn't depend on the length of the string contained by `name` – Alan Birtles Aug 24 '21 at 14:57
  • 2
    `std::string` also has a fixed size, it just has pointers to dynamically allocated memory. – mediocrevegetable1 Aug 24 '21 at 14:57
  • *but what if class A had a container inside of it as well? Then it would be impossible to reserve the correct amount of memory right?* See [this](https://stackoverflow.com/questions/55478523/how-does-stdvector-support-contiguous-memory-for-custom-objects-of-unknown-siz/55478808#55478808) for why that is not an issue – NathanOliver Aug 24 '21 at 15:15
  • The other scenario that is usually mentioned in questions like these is "What about `std::vector`, how can it know how big the derived classes are? The answer being "Polymorphism necessitates using *pointers* or *references*, otherwise you will get object slicing." – Eljay Aug 24 '21 at 15:20
  • Hint: using `sizeof` and the template parameter will give you the size, in bytes, of one element. For example, with `std::vector`, the `sizeof(int)` will return the size of one element. – Thomas Matthews Aug 24 '21 at 16:42

1 Answers1

2

The container knows the size of the element type by virtue of knowing the definition of that type. There is an operator in C++ that returns the size of a complete (i.e. defined) type. sizeof(T) returns the size of the type T.

what if class A had a container inside of it as well? Then it would be impossible to reserve the correct amount of memory right?

That wouldn't be a problem at all. The size of all types is constant in C++.

eerorika
  • 232,697
  • 12
  • 197
  • 326