title: C++ vector passed by value: did I get it right?
body: <p>Let's say I have a struct like this:</p>
  
  <pre><code>struct typeA
  {
      long first;
      string second
      double third;
  };
  </code></pre>
  
  <p>If I declare</p>
  
  <pre><code>typeA myArray[100];
  </code></pre>
  
  <p>Then myArray is stored in the stack, consuming sizeof(typeA)*100 bytes of garbage data (until I store some actual data, at least).</p>
  
  <p>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.</p>
  
  <p>But if I declare</p>
  
  <pre><code>vector&lt;int&gt; myVector (4, 100);
  </code></pre>
  
  <p>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.</p>
  
  <p>Whenever I pass this vector as a parameter, if I add it to the parameter list like this:</p>
  
  <pre><code>vector&lt;int&gt; parameterVector
  </code></pre>
  
  <p>the function gets a <strong>copy of the myVector object</strong> and stores it in the stack.</p>
  
  <p>But if I do it like this:</p>
  
  <pre><code>vector&lt;int&gt; &amp;parameterVector
  </code></pre>
  
  <p>the function gets a <strong>reference to myVector</strong> 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.</p>
  
  <p>Is this correct?</p>
  
  <p>I have a few doubts here:</p>
  
  <ol>
  <li>Do the actual elements get stored in a static array (the ones inherited from C, indicated with square brackets) in the heap?</li>
  <li>Does the myVector object have just one pointer to the first element, or it has multiple pointers to each one of the elements?</li>
  <li>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?</li>
  <li>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).</li>
  </ol>
  
  <p>Thanks! </p>