0

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
Stefan B
  • 541
  • 2
  • 6
  • 13
  • 1
    As for the *why?*: Standard says so. – Baum mit Augen Aug 03 '17 at 00:08
  • 1
    If you are asking how `std::vector` implements deep-copy, please make that more clear. You'd most likely also want to be more specific about what exactly you don't understand. – Baum mit Augen Aug 03 '17 at 00:10
  • A `std::vector` should be thought of as a primitive object, not as a combination of a pointer plus control data. Thus copies always copy everything, not just the pointer and control data. – Ken Y-N Aug 03 '17 at 00:15
  • Think on what would happen to the original when the destructor of the copy ran on exiting from the function if both copies pointed at the same data set. – user4581301 Aug 03 '17 at 00:39
  • 1
    The vector passed by value is a different vector. 'by value' means you do not want Foo() to be able to change the original. – 2785528 Aug 03 '17 at 00:43

0 Answers0