5

Hello I am comming from c to c++ and I've been wondering why can std::vector be passed by value.

I assume passing dynamicaly allocated array by value is not possible as that would only copy the pointer.

How is it then possible for a vector to be coppied, if inside of a vector class is same pointer. It has to somehow know how to reconstruct it into another object.

Franta_B
  • 55
  • 3
  • 1
    For the basic, think about *copy-construction*. Any decent book or tutorial should have mentioned it. If your book doesn't, then [here's a list of decent books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Jul 15 '20 at 19:52
  • Copying an object of a class type invokes its copy constructor, and `std::vector`'s copy constructor copies the underlying array. – Miles Budnek Jul 15 '20 at 19:52

1 Answers1

4

std::vector knows how many elements are stored in the dynamic memory. It is a simple matter to allocate a new buffer of that size and copy the contents into that new memory. All of this happens in the copy constructor.

jkb
  • 2,376
  • 1
  • 9
  • 12