Let's say I have a struct like this:
struct typeA
{
long first;
string second
double third;
};
If I declare
typeA myArray[100];
Then myArray is stored in the stack, consuming sizeof(typeA)*100 bytes of garbage data (until I store some actual data, at least).
Whenever I pass this array as a parameter, I'll always be passing a pointer to the first of the first element in the stack. So the pointer goes from stack to stack.
But if I declare
vector<int> myVector (4, 100);
Then the myVector object is actually stored in the stack, and it contains a pointer to the first element of an array of 4*sizeof(int) bytes stored in the heap, where the actual data is stored. So pointer goes from stack to heap.
Whenever I pass this vector as a parameter, if I add it to the parameter list like this:
vector<int> parameterVector
the function gets a copy of the myVector object and stores it in the stack.
But if I do it like this:
vector<int> ¶meterVector
the function gets a reference to myVector stored in the stack, so I now have a variable stored in the stack, referencing a myVector object also stored in the stack, that contains a pointer to an array of actual elements stored in the heap.
Is this correct?
I have a few doubts here:
- Do the actual elements get stored in a static array (the ones inherited from C, indicated with square brackets) in the heap?
- Does the myVector object have just one pointer to the first element, or it has multiple pointers to each one of the elements?
- So passing a vector by value doesn't pose much of a problem, since the only thing that gets copied is the vector object, but not the actual elements. Is that so?
- If I got the whole thing wrong and the actual elements are copied as well when passing a vector parameter by value, then why does C++ allow this, considering it discourages it with static arrays? (as far as I know, static arrays always get passed as a reference to the first element).
Thanks!
vector<typeA> ¶meterVectordeclaredparameterVectorto be a reference to a vector oftypeAelements, not a pointer. - Some programmer dudevector<typeA> myVector (4, 100), that's not a valid declaration. It tries to create a vector of four elements, each element initialized to100. But you can't initialize atypeAobject to100. - Some programmer dudeint,char*etc are passed. Vectors are not special in that they simply follow the same rule. It is C-style arrays that are the odd-ball, by being inconsistent with everything else. - Neil Kirk