5
votes

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.

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. - Some programmer dude
Copying an object of a class type invokes its copy constructor, and std::vector's copy constructor copies the underlying array. - Miles Budnek

1 Answers

4
votes

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.