Based on my understanding, the vector allocates the memory to store the elements on the heap. Since the vector stores the elements in an array, shouldn't just the internal pointer of the array be copied, when I pass the vector as value. Consider the following code:
#include <iostream>
#include <vector>
void Foo(std::vector<int> input)
{
for (int i = 0; i < input.size(); ++i)
{
std::cout << &input[i] << std::endl; //Print address of each element
}
}
int main()
{
std::vector<int> test{ 1,2,3,4,5,6 }; //Create Vector
for (int i = 0; i < test.size(); ++i)
{
std::cout << &test[i] << std::endl; //Print address of each element
}
std::cout << "----------------" << std::endl;
Foo(test); //Pass by Value
std::cin.get();
}
As output I get
01445358
0144535C
01445360
01445364
01445368
0144536C
----------------
0144F110
0144F114
0144F118
0144F11C
0144F120
0144F124
I understand that the vector object is copied and thus has a different address but since the elements are stored on the heap and accessed by the int* pointing to the array holding the elements, shouldn't the elements have the same address?
Consider the following scenario which works as expected:
struct Array
{
int* elements; //pointer to array
Array(int* e) : elements{ e } { }
};
void Test(Array input)
{
for (int i = 0; i < 5; ++i)
{
std::cout << &input.elements[i] << std::endl; //print address of array
}
}
int main()
{
int* arr = new int[5]; //array on heap
Array t(arr);
for (int i = 0; i < 5; ++i)
{
std::cout << &t.elements[i] << std::endl; //print address of array
}
std::cout << "-------------" << std::endl;
Test(t); //pass by value
std::cin.get();
}
Output:
011A4728
011A472C
011A4730
011A4734
011A4738
-------------
011A4728
011A472C
011A4730
011A4734
011A4738
Why does this print the same address and the first does not?