0

In Java, if you have the following code, list1 and list2 end up pointing to the same object, so a change in list2 will result in a change in list1.

ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2 = list1;
list2.set(0, 10);

for(int i =0; i<list1.size(); i++){
    System.out.println(list1.get(i));
}
for(int i =0; i<list2.size(); i++){
    System.out.println(list2.get(i));
}

And the output ends up being:

10
2
3

10
2
3

However, in C++, the behavior is different?

vector<int> list1;
list1.push_back(1);
list1.push_back(2);
list1.push_back(3);
vector<int> list2;
list2 = list1;
list2.at(0) = 10;
for(int i =0; i<list1.size(); i++){
    cout << list1[i] << endl;
}

for(int i=0; i<list2.size(); i++){
    cout << list2[i] << endl;
}

The output ends up being:

1
2
3

10
2
3

Can someone explain?

Danny Liu
  • 499
  • 2
  • 5
  • 12

3 Answers3

3

To elaborate on my comment:

In Java, the = operator on (assignment-compatible) reference types simply copies the reference value. (Think pointer if you're coming from the C/C++ world.) The key thing to keep in mind is that in Java, no variable is ever an object; it is either a primitive value or a reference to an object.

In your C++ example, the = operator is working on actual objects, not on references. (With other data types, the story might be different.) From the docs for std::vector::operator=:

Assigns new contents to the container, replacing its current contents, and modifying its size accordingly.

So in C++, list2 remains a separate vector object after the assignment, just with a copy of the contents of list1. In Java, the second ArrayList object you assigned to list2 becomes garbage once you reassign list2 to be a reference to the same object as list1.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

To explain simply:

Java uses reference semantics. In this case you have two names (list1, list2) for the same object after the line list2 = list1.

C++ uses value semantics. The values of list1 are copied to list2 and you have a new unrelated object (list2) that may be mutated without affecting the copied object(list1).

evansjohnson
  • 452
  • 4
  • 14
1

The simplest way to have the same behavior in C++ is to declare list2 as a reference - however, this requires that the assignment occur in list2's declaration and not after:

vector<int> &list2 = list1;
Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28